package com.info.zhiduoduo.admin.service;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.Condition;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.google.common.collect.Lists;
import com.info.zhiduoduo.admin.model.dto.account.QuarterBusinessGrossDto;
import com.info.zhiduoduo.common.constants.company.*;
import com.info.zhiduoduo.core.service.*;
import com.info.zhiduoduo.repository.dto.company.RequestRefundListDto;
import com.info.zhiduoduo.admin.model.dto.common.BatchManualErrorDto;
import com.info.zhiduoduo.admin.model.dto.kingdee.ExportReceiptDto;
import com.info.zhiduoduo.admin.model.formbean.account.CompanyAccountBalanceFormBean;
import com.info.zhiduoduo.admin.model.formbean.account.CompanyAccountFlowFormBean;
import com.info.zhiduoduo.admin.model.formbean.account.NotUpStandardMakerFormBean;
import com.info.zhiduoduo.admin.model.formbean.account.RenewTradeFormBean;
import com.info.zhiduoduo.admin.model.formbean.account.RenewWithdrawFormBean;
import com.info.zhiduoduo.admin.model.formbean.account.SaveHandleRecordFormBean;
import com.info.zhiduoduo.admin.model.formbean.account.TradeRecordListFormBean;
import com.info.zhiduoduo.admin.model.formbean.account.UserAccountFlowFormBean;
import com.info.zhiduoduo.admin.model.formbean.account.WithdrawListFormBean;
import com.info.zhiduoduo.admin.model.formbean.common.BatchManualErrorFormBean;
import com.info.zhiduoduo.admin.model.formbean.company.*;
import com.info.zhiduoduo.admin.model.formbean.maker.HandleRescissionApplyFormBean;
import com.info.zhiduoduo.common.configs.CommonConfig;
import com.info.zhiduoduo.common.configs.KingdeeTemplateConfig;
import com.info.zhiduoduo.common.configs.PayConfig;
import com.info.zhiduoduo.common.configs.RechargeNotifyConfig;
import com.info.zhiduoduo.common.configs.ZddUrlConfig;
import com.info.zhiduoduo.common.constants.Constants;
import com.info.zhiduoduo.common.constants.SmartResult;
import com.info.zhiduoduo.common.constants.StatusMsg;
import com.info.zhiduoduo.common.constants.crowdsource.CrowdsourceUserType;
import com.info.zhiduoduo.common.constants.maker.MakerType;
import com.info.zhiduoduo.common.constants.partner.PartnerCrowdsourceCostState;
import com.info.zhiduoduo.common.constants.project.CalcAmountType;
import com.info.zhiduoduo.common.constants.project.CompanyProjectState;
import com.info.zhiduoduo.common.exception.Asserts;
import com.info.zhiduoduo.common.formbean.BaseListFormBean;
import com.info.zhiduoduo.common.formbean.BaseSimpleFormBean;
import com.info.zhiduoduo.common.utils.DateUtil;
import com.info.zhiduoduo.common.utils.EasyExcelUtil;
import com.info.zhiduoduo.common.utils.NumberUtil;
import com.info.zhiduoduo.common.utils.RandomUtil;
import com.info.zhiduoduo.common.utils.StringUtil;
import com.info.zhiduoduo.core.configs.Redis.RedisKey;
import com.info.zhiduoduo.core.service.common.BaseService;
import com.info.zhiduoduo.core.service.common.RedisService;
import com.info.zhiduoduo.core.service.payment.thirdpay.ZhaoShangTradeBulterService;
import com.info.zhiduoduo.repository.dto.account.CompanyAccountFlowDto;
import com.info.zhiduoduo.repository.dto.account.CompanyAccountStatisticDto;
import com.info.zhiduoduo.repository.dto.account.CompanyCommissionStatisticDto;
import com.info.zhiduoduo.repository.dto.account.CrowdsourcingLedgerDto;
import com.info.zhiduoduo.repository.dto.account.ExportQuarterStudioDto;
import com.info.zhiduoduo.repository.dto.account.MakerAccountFlowDto;
import com.info.zhiduoduo.repository.dto.account.MonthCrowdSourceTradingVolumeDto;
import com.info.zhiduoduo.repository.dto.account.MonthZhiduoTradingVolumeDto;
import com.info.zhiduoduo.repository.dto.account.NotUpStandardDetailDto;
import com.info.zhiduoduo.repository.dto.account.NotUpStandardMakerDto;
import com.info.zhiduoduo.repository.dto.account.NotUpStandardMakerExcelDto;
import com.info.zhiduoduo.repository.dto.account.ReceiptDto;
import com.info.zhiduoduo.repository.dto.account.TradeRecordBriefDto;
import com.info.zhiduoduo.repository.dto.company.*;
import com.info.zhiduoduo.repository.dto.maker.MakerAlipayPrincipalDto;
import com.info.zhiduoduo.repository.dto.maker.MakerDetailDto;
import com.info.zhiduoduo.repository.dto.maker.MakerStudioPromiseDto;
import com.info.zhiduoduo.repository.dto.pay.PaymentMerchantDto;
import com.info.zhiduoduo.repository.entity.company.*;
import com.info.zhiduoduo.repository.entity.crowdsource.CrowdsourceCompanyParty;
import com.info.zhiduoduo.repository.entity.foreign.ForeignProject;
import com.info.zhiduoduo.repository.entity.foreign.ForeignTradeRecord;
import com.info.zhiduoduo.repository.entity.maker.*;
import com.info.zhiduoduo.repository.entity.memorandum.PlatformMemorandum;
import com.info.zhiduoduo.repository.entity.order.TradeRecord;
import com.info.zhiduoduo.repository.entity.partner.PartnerWithdraw;
import com.info.zhiduoduo.repository.entity.pay.PaymentMerchant;
import com.info.zhiduoduo.repository.entity.recharge.RechargeRecord;
import com.info.zhiduoduo.repository.entity.system.MonthBusinessGross;
import com.info.zhiduoduo.repository.mapper.company.*;
import com.info.zhiduoduo.repository.mapper.crowdsource.CrowdsourceProjectItemMapper;
import com.info.zhiduoduo.repository.mapper.crowdsource.CrowdsourceProjectMapper;
import com.info.zhiduoduo.repository.mapper.entrustmentproject.EntrustmentProjectItemMapper;
import com.info.zhiduoduo.repository.mapper.foreign.ForeignTradeRecordMapper;
import com.info.zhiduoduo.repository.mapper.maker.*;
import com.info.zhiduoduo.repository.mapper.memorandum.PlatformMemorandumMapper;
import com.info.zhiduoduo.repository.mapper.order.TradeRecordMapper;
import com.info.zhiduoduo.repository.mapper.partner.PartnerBrokerageMapper;
import com.info.zhiduoduo.repository.mapper.partner.PartnerMonthlyCrowdCostMapper;
import com.info.zhiduoduo.repository.mapper.partner.PartnerWithdrawMapper;
import com.info.zhiduoduo.repository.mapper.pay.PaymentMerchantMapper;
import com.info.zhiduoduo.repository.mapper.system.MonthBusinessGrossMapper;
import com.info.zhiduoduo.repository.mapper.taxer.TaxerInvoiceMapper;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.LocalDate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
@Transactional
public class AccountService extends BaseService {

	@Resource
	TradeRecordMapper tradeRecordMapper;
	@Resource
	PartnerWithdrawMapper partnerWithdrawMapper;
	@Resource
	CompanyAccountMapper companyAccountMapper;
	@Resource
	CompanyPaymentMapper companyPaymentMapper;
	@Resource
	CompanyProjectMapper companyProjectMapper;
	@Resource
	PartnerBrokerageMapper partnerBrokerageMapper;
	@Resource
	PartnerMonthlyCrowdCostMapper partnerMonthlyCrowdCostMapper;
	@Resource
	CompanyAccountflowMapper companyAccountflowMapper;
	@Resource
	MakerAccountflowMapper makerAccountflowMapper;
	@Resource
	CompanyRechargeMapper companyRechargeMapper;
	@Resource
	MakerMapper makerMapper;
	@Resource
	MakerStudioMapper makerStudioMapper;
	@Resource
	CompanyOfflineRechargeMapper companyOfflineRechargeMapper;
	@Resource
	CompanyOfflineRechargeDetailMapper companyOfflineRechargeDetailMapper;
	@Resource
	ForeignTradeRecordMapper foreignTradeRecordMapper;
	@Resource
	CompanyProjectMapper projectMapper;
	@Resource
	CrowdsourceProjectItemMapper crowdsourceProjectItemMapper;
	@Resource
	EntrustmentProjectItemMapper entrustmentProjectItemMapper;
	@Resource
	MonthBusinessGrossMapper monthBusinessGrossMapper;
	@Resource
	PaymentMerchantMapper paymentMerchantMapper;
	@Resource
	CompanyZhaoshangSubLedgerIncomingRecordMapper companyZhaoshangSubLedgerIncomingRecordMapper;
	@Resource
	EnterpriseRefundMapper enterpriseRefundMapper;

	@Autowired
	WxMessageService wxMessageService;

	@Resource
	CommonService commonService;

	@Autowired
	ProjectService projectService;
	@Autowired
	PartnerService partnerService;
	@Autowired
	CoreProjectService coreProjectService;
	@Autowired
	CorePartnerService corePartnerService;
	@Autowired
	CoreCompanyService coreCompanyService;
	@Autowired
	RedisService redisService;
	@Autowired
	ZhiduoduoProjectService zhiduoduoProjectService;
	@Autowired
	BalanceService balanceService;
	@Autowired
	ZhaoShangTradeBulterService zhaoShangTradeBulterService;
	@Autowired
	MakerService makerService;

	@Autowired
	PayConfig payConfig;
	@Autowired
	ZddUrlConfig zddUrlConfig;
	@Autowired
	RechargeNotifyConfig rechargeNotifyConfig;
	@Autowired
	CommonConfig commonConfig;
	@Resource
	KingdeeTemplateConfig kingdeeTemplateConfig;

	@Resource
	TaxerInvoiceMapper taxerInvoiceMapper;

	@Resource
	CrowdsourceProjectMapper crowdsourceProjectMapper;

	@Resource
	MakerAlipayPrincipalMapper makerAlipayPrincipalMapper;
	@Resource
	CompanyZhaoshangSubLedgerRechargeMapper ledgerRechargeMapper;

	@Resource
	MakerCyCleRecordMapper makerCyCleRecordMapper;
	@Resource
	PlatformMemorandumMapper platformMemorandumMapper;

	/**
	 * 获取代付列表
	 */
	public SmartResult getTradeRecordList(BaseSimpleFormBean<TradeRecordListFormBean> formBean) {
		TradeRecordListFormBean reqdata = formBean.getReqdata();
		if (reqdata == null) return errorParamSmartResult();

		String name = reqdata.getName();
		Date startDate = reqdata.getStartDate();
		Date endDate = reqdata.getEndDate();
		int tradetype = reqdata.getTradetype();
		//交易状态 1:创建中 2:处理中 3:交易成功 4:交易失败 5:交易拒绝
		int tradestate = reqdata.getTradestate();

		if (startDate == null) startDate = new Date(0);
		if (endDate == null) endDate = new Date();

		Page<Object> page = PageHelper.startPage(formBean.getPage(), formBean.getRows());
		List<TradeRecordBriefDto> dtoList = tradeRecordMapper.getTradeRecordList(name, tradetype, tradestate, startDate, endDate);
		dtoList.forEach(dto -> {
			if (2 == dto.getTradestate() && (CompanyPayType.isZhaoShangPayType(dto.getPayId()) || CompanyPayType.isPingAnPayType(dto.getPayId()))) {
				//获取交易时间
				Date transactionTime = dto.getTradetime();
				long differTime = DateUtil.differMinute(DateUtil.DateToStr("yyyy-MM-dd HH:mm:ss", transactionTime),
						DateUtil.DateToStr("yyyy-MM-dd HH:mm:ss", new Date()));
				if (120 < differTime) {
					dto.setWhetherOvertime(2);
				} else {
					dto.setWhetherOvertime(1);
				}
			}
		});
		return smartResult(dtoList, page.getTotal(), page.getPages(), page.getPageNum());
	}

	public SmartResult batchManualError(BaseListFormBean<BatchManualErrorFormBean> formBean) {
		if (null == formBean || null == formBean.getReqdata() || formBean.getReqdata().size() <= 0) {
			return errorParamSmartResult();
		}
		List<BatchManualErrorFormBean> formBeanList = formBean.getReqdata();
		List<BatchManualErrorDto> dtoList = new ArrayList<>();
		formBeanList.forEach(bean -> {
			TradeRecord trade = new TradeRecord().selectById(bean.getTradeid());
			if (null == trade) {
				BatchManualErrorDto dto = new BatchManualErrorDto();
				dto.setTradeid(bean.getTradeid()).setReason(StatusMsg.StatusMsg_444.getMsg());
				dtoList.add(dto);
				return;
			}
			//判断支付状态
			if (Constants.TRADE_IN_PROCESS == trade.getTradestate()) {
				trade.setTradestate(Constants.TRADE_FAIL).setErrormsg("人工处理：" + bean.getReason()).setFinishtime(new Date());
				if (!trade.updateById()) {
					BatchManualErrorDto dto = new BatchManualErrorDto();
					dto.setTradeid(bean.getTradeid()).setReason(StatusMsg.StatusMsg_199.getMsg());
					dtoList.add(dto);
				}
			} else {
				BatchManualErrorDto dto = new BatchManualErrorDto();
				dto.setTradeid(bean.getTradeid()).setReason(StatusMsg.StatusMsg_448.getMsg());
				dtoList.add(dto);
			}
		});
		return smartResult(dtoList);
	}

	/**
	 * 交易失败后，重新提交交易
	 */
	public SmartResult repayTrade(BaseSimpleFormBean<RenewTradeFormBean> formBean) {
		RenewTradeFormBean reqdata = formBean.getReqdata();
		if (reqdata == null) return errorParamSmartResult();

		int userid = reqdata.getUserid();
		int idtype = reqdata.getIdtype();
		int projectid = reqdata.getProjectid();
		int tradeid = reqdata.getTradeid();

		TradeRecord oldTrade = new TradeRecord().selectById(tradeid);
		if (oldTrade == null || NumberUtil.safeInt(oldTrade.getProjectid()) != projectid || userid != oldTrade.getUserid() ||
				idtype != oldTrade.getIdtype()) {
			return errorParamSmartResult();
		}

		CompanyProject project = new CompanyProject().selectById(projectid);
		if (project == null) return smartResult(StatusMsg.StatusMsg_301);
		if (project.getState() != CompanyProjectState.CHECKED) return smartResult(StatusMsg.StatusMsg_303);

		int oldState = NumberUtil.safeInt(oldTrade.getTradestate());
		if (oldState == Constants.TRADE_CREATE || oldState == Constants.TRADE_IN_PROCESS) {
			return smartResult(StatusMsg.StatusMsg_448);
		} else if (oldState == Constants.TRADE_SUCCESS) {
			return smartResult(StatusMsg.StatusMsg_449);
		}

		if (oldTrade.getRepay() == Constants.TRUE) return smartResult(StatusMsg.StatusMsg_450);

		//重新提交支付，新建一条交易记录
		SmartResult smartResult = zhiduoduoProjectService.handleRepayUser(project);

		if (smartResult != null && smartResult.isSuccessful()) {
			oldTrade.setRepay(1).setAdminid(formBean.getUserid()).updateById();
			return smartResult;
		}

		return optFailSmartResult();
	}

	/**
	 * 获取代付列表
	 */
	public SmartResult getForeignTradeRecordList(BaseSimpleFormBean<TradeRecordListFormBean> formBean) {
		TradeRecordListFormBean reqdata = formBean.getReqdata();
		if (reqdata == null) return errorParamSmartResult();

		String name = reqdata.getName();
		Date startDate = reqdata.getStartDate();
		Date endDate = reqdata.getEndDate();
		int tradetype = reqdata.getTradetype();
		//交易状态 1:创建中 2:处理中 3:交易成功 4:交易失败 5:交易拒绝
		int tradestate = reqdata.getTradestate();

		if (startDate == null) startDate = new Date(0);
		if (endDate == null) endDate = new Date();

		Page<Object> page = PageHelper.startPage(formBean.getPage(), formBean.getRows());
		foreignTradeRecordMapper.getTradeRecordList(name, tradetype, tradestate, startDate, endDate);
		return smartResultPage(page);
	}

//	/**
//	 * 交易失败后，重新提交交易
//	 */
//	public SmartResult repayForeignProjectTrade(BaseSimpleFormBean<RenewTradeFormBean> formBean) {
//		RenewTradeFormBean reqdata = formBean.getReqdata();
//		if (reqdata == null) return errorParamSmartResult();
//
//		int userid = reqdata.getUserid();
//		int idtype = reqdata.getIdtype();
//		int projectid = reqdata.getProjectid();
//		int tradeid = reqdata.getTradeid();
//
//		ForeignTradeRecord oldTrade = new ForeignTradeRecord().selectById(tradeid);
//		if (oldTrade == null || NumberUtil.safeInt(oldTrade.getProjectId()) != projectid || userid != oldTrade.getUserid() ||
//				idtype != oldTrade.getIdtype()) {
//			return errorParamSmartResult();
//		}
//
//		ForeignProject project = new ForeignProject().selectById(projectid);
//		if (project == null) return smartResult(StatusMsg.StatusMsg_301);
//		if (project.getState() != CompanyProjectState.CHECKED) return smartResult(StatusMsg.StatusMsg_303);
//
//		int oldState = NumberUtil.safeInt(oldTrade.getTradestate());
//		if (oldState == Constants.TRADE_CREATE || oldState == Constants.TRADE_IN_PROCESS) {
//			return smartResult(StatusMsg.StatusMsg_448);
//		} else if (oldState == Constants.TRADE_SUCCESS) {
//			return smartResult(StatusMsg.StatusMsg_449);
//		}
//
//		if (oldTrade.getRepay() == Constants.TRUE) return smartResult(StatusMsg.StatusMsg_450);
//
//		//重新提交支付，新建一条交易记录
//		SmartResult smartResult = null;
//		Integer businessType = oldTrade.getBusinessType();
//		if (businessType == Constants.KLT_PAY_BUSINESS_TYPE_USER_AMOUNT) smartResult = foreignProjectPaymentService.payProject(project);
//
//		if (smartResult != null && smartResult.isSuccessful()) {
//			oldTrade.setRepay(1).updateById();
//			return smartResult;
//		}
//
//		return optFailSmartResult();
//	}

	/**
	 * 获取提现列表
	 */
	public SmartResult getWithdrawList(BaseSimpleFormBean<WithdrawListFormBean> formBean) {
		WithdrawListFormBean reqdata = formBean.getReqdata();
		if (reqdata == null) return errorParamSmartResult();

		String name = reqdata.getName();
		Date startDate = reqdata.getStartDate();
		Date endDate = reqdata.getEndDate();
		//交易状态 1:创建中 2:处理中 3:交易成功 4:交易失败 5:交易拒绝
		int state = reqdata.getState();

		if (startDate == null) startDate = new Date(0);
		if (endDate == null) endDate = new Date();

		Page<Object> page = PageHelper.startPage(formBean.getPage(), formBean.getRows());
		partnerWithdrawMapper.getWithdrawList(name, state, startDate, endDate);
		return smartResultPage(page);
	}

	/**
	 * 提现交易失败后，重新提交提现交易
	 */
	public SmartResult repayWithdraw(BaseSimpleFormBean<RenewWithdrawFormBean> formBean) {
		RenewWithdrawFormBean reqdata = formBean.getReqdata();
		if (reqdata == null) return errorParamSmartResult();

		int wdid = reqdata.getWdid();
		int partnerid = reqdata.getPartnerid();

		PartnerWithdraw oldWithdraw = new PartnerWithdraw().selectById(wdid);
		if (oldWithdraw == null) return errorParamSmartResult();

		int oldState = NumberUtil.safeInt(oldWithdraw.getState());
		if (oldState == Constants.TRADE_CREATE || oldState == Constants.TRADE_IN_PROCESS) {
			return smartResult(StatusMsg.StatusMsg_448);
		} else if (oldState == Constants.TRADE_SUCCESS) {
			return smartResult(StatusMsg.StatusMsg_449);
		}

		if (oldWithdraw.getRepay() == 1) return smartResult(StatusMsg.StatusMsg_450);

		//重新提交提现记录，新建一条提现记录
		SmartResult smartResult = corePartnerService.handleWithdrawInternal(wdid, partnerid);
		if (smartResult.getState() == StatusMsg.StatusMsg_100.getState()) {
			oldWithdraw.setRepay(1).updateById();
		}

		return smartResult;
	}

	/**
	 * 创建企业充值
	 */
	public SmartResult createRecharge(BaseSimpleFormBean<CreateRechargeFormBean> formBean) {
		CreateRechargeFormBean reqdata = formBean.getReqdata();
		if (reqdata == null || reqdata.getAmount() == null) return errorParamSmartResult();

		//检查企业是否存在
		Company company = new Company().selectById(reqdata.getCompid());
		Asserts.notNull(company,StatusMsg.StatusMsg_302);
		//检查支付方式是否存在
		Asserts.isTrue(!NumberUtil.isAnyZero(reqdata.getPayId()), StatusMsg.StatusMsg_454);

		CompanyRecharge recharge;
		if (reqdata.getRechargeid() > 0) {
			//编辑, 则判断必须是申请中的才能编辑
			recharge = new CompanyRecharge().selectById(reqdata.getRechargeid());
			if (recharge.getState() != Constants.RECHARGE_APPLYING) return smartResult(StatusMsg.StatusMsg_309);

			BeanUtils.copyProperties(reqdata, recharge);
		} else {
			if (reqdata.getAmount().doubleValue() > 0) {
				int exists = new CompanyRecharge().selectCount(Condition.create().eq("receiptno", reqdata.getReceiptno()));
				if (exists > 0) return smartResult(StatusMsg.StatusMsg_312);
			}

			recharge = new CompanyRecharge();
			BeanUtils.copyProperties(reqdata, recharge);

			String rechargeno = RandomUtil.createRandomNo("REC", "");
			recharge.setRechargeno(rechargeno);
		}
		//获取主体信息
		CrowdsourceCompanyParty party = new CrowdsourceCompanyParty().selectById(reqdata.getSubjectId());
		if (null == party) {
			return smartResult(StatusMsg.StatusMsg_344);
		}
		recharge.setPayId(reqdata.getPayId())
				.setSubjectCode(party.getKingdeeCustomerCode())
				.setCreateAdminid(formBean.getUserid());
		try {
			if (recharge.insertOrUpdate()) {
				return smartResult(recharge.getRechargeid());
			}
		} catch (Exception e) {
			//异常,可能是单号唯一性冲突
			log.error("创建充值订单失败", e);
		}

		return optFailSmartResult();
	}

	public void exportCompanyRechargeFlow(HttpServletResponse response, Date startDate, Date endDate) {
		//获取模板路径
		String templatePath = kingdeeTemplateConfig.getReceiptTemplatePath();
		List<ExportReceiptDto> dtoList = new ArrayList<>();
		List<ReceiptDto> receiptDtoList = companyRechargeMapper.queryReceiptDto(startDate, endDate);
		if (null != receiptDtoList && receiptDtoList.size() > 0) {
			//序号默认从100000开始
			int number = 100000;
			//金额格式化
			DecimalFormat df = new DecimalFormat("##,##0.00");
			for (ReceiptDto dto : receiptDtoList) {
				number = number + 1;
				String date = DateUtil.DateToStr("yyyy-MM-dd", dto.getCreatetime());
				String amount = df.format(dto.getAmount());
				ExportReceiptDto exportReceiptDto = ExportReceiptDto.of(number, dto, date, amount);
				dtoList.add(exportReceiptDto);
			}
		}
		String fileName = "附件一：收款单" + DateUtil.DateToStr("yyyy-MM-dd", new Date());
		try {
			EasyExcelUtil.exportComplex(response, templatePath, fileName, dtoList);
		} catch (Exception e) {
			e.printStackTrace();
			log.error("导出收款单失败");
		}
	}

	/**
	 * 删除充值记录, 如果已完成则不能删除
	 */
	public SmartResult delRecharge(BaseSimpleFormBean<Integer> formBean) {
		Integer rechargeid = formBean.getReqdata();
		if (rechargeid == null || rechargeid <= 0) return errorParamSmartResult();

		CompanyRecharge recharge = new CompanyRecharge().selectById(rechargeid);
		if (recharge.getState() == 2 || recharge.getState() == 3) return smartResult(StatusMsg.StatusMsg_309);

		recharge.deleteById();
		return smartResult();
	}

	/**
	 * 充值记录列表
	 */
	public SmartResult getRechargeList(BaseSimpleFormBean<RechargeListFormBean> formBean) {
		RechargeListFormBean reqdata = formBean.getReqdata();
		if (reqdata == null) return errorParamSmartResult();

		String name = reqdata.getName();
		String state = reqdata.getState();
		Date startDate = reqdata.getStartDate();
		Date endDate = reqdata.getEndDate();

		if (startDate == null) startDate = new Date(0);
		if (endDate == null) endDate = new Date();

		Page<Object> page = PageHelper.startPage(formBean.getPage(), formBean.getRows());
		List<CompanyRechargeDto> rechargeList = companyRechargeMapper.getRechargeList(name, state, startDate, endDate);

		return smartResult(rechargeList, page.getTotal(), page.getPages(), page.getPageNum());
	}

	/**
	 * 充值记录列表
	 */
	public void downloadRechargeList(BaseSimpleFormBean<RechargeListFormBean> formBean, HttpServletResponse response) {
		RechargeListFormBean reqdata = formBean.getReqdata();
		if (reqdata == null) {
			response.setStatus(HttpServletResponse.SC_NOT_FOUND);
			return;
		}

		String name = reqdata.getName();
		String state = reqdata.getState();
		Date startDate = reqdata.getStartDate();
		Date endDate = reqdata.getEndDate();

		if (startDate == null) startDate = new Date(0);
		if (endDate == null) endDate = new Date();

		List<CompanyRechargeDto> rechargeList = companyRechargeMapper.getRechargeList(name, state, startDate, endDate);

		EasyExcelUtil.download(response, "充值列表", CompanyRechargeDto.class, rechargeList);
	}

	/**
	 * 确认充值完成,同步锁,防止2个请求同时操作一个充值记录
	 */
	public synchronized SmartResult confirmRecharge(BaseSimpleFormBean<ConfirmRechargeFormBean> formBean) {
		ConfirmRechargeFormBean reqdata = formBean.getReqdata();

		if (reqdata == null) return errorParamSmartResult();

		int rechargeid = reqdata.getRechargeid();
		String receiptno = reqdata.getReceiptno();
		BigDecimal amount = reqdata.getAmount();
		String verifycode = reqdata.getVerifycode();

		if (StringUtil.isEmpty(reqdata.getVerifycode()) || rechargeid <= 0 || amount == null) {
			return errorParamSmartResult();
		}

		//充值记录是否存在
		CompanyRecharge recharge = new CompanyRecharge().selectById(rechargeid);
		if (recharge == null) return smartResult(StatusMsg.StatusMsg_320);

		if (recharge.getState() == Constants.RECHARGE_PROCESSING) {
			return smartResult(StatusMsg.StatusMsg_321);
		} else if (recharge.getState() == Constants.RECHARGE_CONFIRMED) {
			return smartResult(StatusMsg.StatusMsg_322);
		}

		//企业账户是否存在
		Integer compid = recharge.getCompid();
		Company company = new Company().selectById(compid);
		CompanyAccount account = new CompanyAccount().selectOne(Condition.create().eq("compid", compid));
		if (account == null) return smartResult(StatusMsg.StatusMsg_302);

		//判断验证码正确或是否超时
		if (verifycode.equals("zdd*()!@#")) {
			// 默认验证码
		} else {
			String savedCode = redisService.getString(RedisKey.genRechargeVerifyCodeKey(rechargeid));

			if (StringUtil.isEmpty(savedCode)) {
				return smartResult(StatusMsg.StatusMsg_112);
			} else if (!StringUtil.equals(savedCode, verifycode)) {
				return smartResult(StatusMsg.StatusMsg_106);
			}
		}

		//判断回执单和金额是否一致
		if (receiptno == null) receiptno = "";
		String savedReceiptno = recharge.getReceiptno();
		if (savedReceiptno == null) savedReceiptno = "";

		if (recharge.getAmount().compareTo(amount) != 0) {
			return smartResult(StatusMsg.StatusMsg_307);
		} else if (!StringUtil.equals(receiptno, savedReceiptno)) {
			return smartResult(StatusMsg.StatusMsg_308);
		}

		// 查询账户余额
		CompanyPayment companyPayment = companyPaymentMapper.getCompanyPayment(compid, recharge.getPayId());
		if(companyPayment == null){
			// 新建账户余额
			companyPayment = new CompanyPayment().setBalance(BigDecimal.ZERO)
												 .setFrozenBalance(BigDecimal.ZERO)
												 .setCompid(recharge.getCompid())
												 .setPayId(recharge.getPayId());
			companyPayment.insert();
		}

		//账户余额增加
		BigDecimal beforeBalance = companyPayment.getBalance();
		BigDecimal beforeFrozenBalance = companyPayment.getFrozenBalance();
		BigDecimal currBalance = amount.add(beforeBalance);
		if (currBalance.compareTo(BigDecimal.ZERO) < 0) {
			// 充值后余额不能为负数
			return smartResult(StatusMsg.StatusMsg_328);
		}

		if (new CompanyRecharge().setRechargeid(rechargeid).setState(Constants.RECHARGE_PROCESSING).updateById()) {

			companyPayment.setBalance(currBalance);
			BigDecimal currFrozenBalance = companyPayment.getFrozenBalance();

			if (companyPayment.updateById()) {
				//确认完成,生成企业流水
				boolean isRealRecharge = amount.doubleValue() > 0;
				String flowname = isRealRecharge ? Constants.ACCT_FLOW_RECHARGE : recharge.getRemark();
				boolean insertFLow = new CompanyAccountflow().setCompid(recharge.getCompid())
						.setFlowAmount(amount)
						.setBeforeBalance(beforeBalance)
						.setCurrBalance(currBalance)
						.setBeforeFrozenBalance(beforeFrozenBalance)
						.setCurrFrozenBalance(currFrozenBalance)
						.setBizid(rechargeid)
						.setBizType(CompanyAccountFlowBizType.RECHARGE)
						.setFlowtype(1)
						.setFlowname(flowname)
						.setPayId(recharge.getPayId())
						.insert();

				//充值完成状态
				boolean updateRecharge = new CompanyRecharge().setRechargeid(rechargeid)
						.setState(Constants.RECHARGE_CONFIRMED)
						.setRechargetime(new Date())
						.setUpdateAdminid(formBean.getUserid())
						.updateById();

				if (insertFLow && updateRecharge) {
					//成功发送通知
					if (isRealRecharge) {
						new Thread(() -> {
							String info = String.format("【%s】，充值金额：【%s】元", company.getCompname(), recharge.getAmount());
							// 给顾问发企信消息
							commonService.sendEnterpriseWeChatNotice(account.getBusinessManagerId(), company.getCompname(), 1, info);
							// 通知企业
							wxMessageService.notifyCompanyRecharged(rechargeid);
						}).start();
					}

					return smartResult();
				} else {
					try {
						throw new RuntimeException("生成企业流水失败");
					} catch (RuntimeException e) {
						e.printStackTrace();
						//手动回滚
						TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
					}
				}
			} else {
				try {
					throw new RuntimeException("企业账户余额更新失败");
				} catch (RuntimeException e) {
					e.printStackTrace();
					//手动回滚
					TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
				}
			}

		}

		//走到这里,说明失败了
		return optFailSmartResult();
	}

	/**
	 * 获取充值详情
	 */
	public SmartResult getRechargeDetail(BaseSimpleFormBean<Integer> formBean) {

		CompanyRechargeDto rechargeDetail = companyRechargeMapper.getRechargeDetail(formBean.getReqdata());
		return smartResult(rechargeDetail);
	}

	/**
	 * 发送充值验证码,微信模板消息
	 */
	public SmartResult sendRechargeVerifyCode(BaseSimpleFormBean<Integer> formBean) {
		Integer rechargeid = formBean.getReqdata();
		if (rechargeid == null || rechargeid <= 0) return errorParamSmartResult();

		//发送验证码
		String verifycode = RandomUtil.getRandomNum(4);
		redisService.set(RedisKey.genRechargeVerifyCodeKey(rechargeid), verifycode, 10 * 60);

		//发送验证码模板消息
		wxMessageService.sendVerifycode(rechargeid, verifycode);
		return smartResult();
	}

	/**
	 * 获取企业账户流水
	 */
	public SmartResult getCompanyAccountFlow(BaseSimpleFormBean<CompanyAccountFlowFormBean> formBean) {
		CompanyAccountFlowFormBean reqdata = formBean.getReqdata();
		if (reqdata == null) return errorParamSmartResult();

		String name = reqdata.getName();
		int flowtype = reqdata.getFlowtype();
		Date startDate = reqdata.getStartDate();
		Date endDate = reqdata.getEndDate();

		if (startDate == null) startDate = new Date(0);
		if (endDate == null) endDate = new Date();

		SimpleDateFormat sdf;
		Page<Object> page = PageHelper.startPage(formBean.getPage(), formBean.getRows());
		List<CompanyAccountFlowDto> list = companyAccountflowMapper.getAccountFlowList(name, flowtype, reqdata.getAccountType(), startDate,
				endDate);
		if (CollectionUtils.isNotEmpty(list)) {
			for (CompanyAccountFlowDto flow : list) {
				if (flow.getBizType() == CompanyAccountFlowBizType.ZDD_PROJECT) {
					CompanyProject companyAccount = companyAccountflowMapper.getMakerLedger(flow.getBizid());
					if (companyAccount != null) {
						flow.setRealname(companyAccount.getRealname())
								.setUsername(companyAccount.getUsername())
								.setProjectpayamount(companyAccount.getProjectPayAmount())
								.setProjectdealamount(companyAccount.getProjectdealamount());
					}
				} else if (NumberUtil.intIn(flow.getBizType(),CompanyAccountFlowBizType.CROWDSOURCE_PROJECT,CompanyAccountFlowBizType.CROWDSOURCE_ODD_PROJECT)) {
					flow.setItemList(companyAccountflowMapper.getCrowdsourcingLedger(flow.getBizid()));
				} else if (flow.getBizType() == CompanyAccountFlowBizType.GROUPON_PROJECT) {
					CrowdsourcingLedgerDto dto = companyAccountflowMapper.getGroupMakerByBizId(flow.getBizid(), flow.getItemId());
					flow.setRealname(dto.getRealname())
							.setUsername(dto.getUsername())
							.setProjectpayamount(dto.getProjectamount())
							.setProjectdealamount(dto.getIntegratedtaxfee());
				} else if (flow.getBizType() == CompanyAccountFlowBizType.ENTRUST_PROJECT) {
					CrowdsourcingLedgerDto dto = companyAccountflowMapper.getEntrustmentByBizId(flow.getBizid(), flow.getItemId());
					flow.setRealname(dto.getRealname())
							.setUsername(dto.getUsername())
							.setProjectpayamount(dto.getProjectamount())
							.setProjectdealamount(dto.getIntegratedtaxfee());
				}
			}
		}

		return smartResultPage(page);
	}

	/**
	 * 获取企业创客团账本流水
	 */
	public SmartResult getCompanyMakerGrouponAccountFlow(BaseSimpleFormBean<CompanyAccountFlowFormBean> formBean) {
		CompanyAccountFlowFormBean reqdata = formBean.getReqdata();
		if (reqdata == null) return errorParamSmartResult();

		String name = reqdata.getName();
		int flowtype = reqdata.getFlowtype();
		Date startDate = reqdata.getStartDate();
		Date endDate = reqdata.getEndDate();

		if (startDate == null) startDate = new Date(0);
		if (endDate == null) endDate = new Date();

		Page<Object> page = PageHelper.startPage(formBean.getPage(), formBean.getRows());
		companyAccountflowMapper.getAccountFlowList(name, flowtype, CompanyAccountFlowAccountType.makerGroupType(), startDate, endDate);

		return smartResultPage(page);
	}

	/**
	 * 获取企业账户余额列表
	 */
	public SmartResult<CompanyAccountBriefDto> getCompanyAccountBalanceList(BaseSimpleFormBean<CompanyAccountBalanceFormBean> formBean) {
		CompanyAccountBalanceFormBean reqdata = formBean.getReqdata();
		if (reqdata == null) return errorParamSmartResult();

		String name = reqdata.getName();

		Page<CompanyAccountBriefDto> page = PageHelper.startPage(formBean.getPage(), formBean.getRows());
		companyAccountMapper.getAccountBalanceList(name);
		page.stream()
				//增加 进行中，验收中的项目款小计； 所有未体现的合伙人佣金小计
				.peek(accountBriefDto -> accountBriefDto.setUnsettledProjectAmount(
								companyProjectMapper.getUnsettledProjectAmount(accountBriefDto.getCompid()))
						.setUnwithdrawBrokerageAmount(
								partnerBrokerageMapper.getunwithdrawNormalBrokerageAmount(accountBriefDto.getCompid())))
				.collect(Collectors.toList());

		return smartResultPage(page);
	}

	public SmartResult<CompanyAccountStatisticDto> getAllCompanyAccountStatistic(BaseSimpleFormBean formBean) {

		BigDecimal unsettledProjectAmount = companyProjectMapper.getUnsettledProjectAmount(0);
		BigDecimal unwithDrawBrokerageAmount = partnerBrokerageMapper.getunwithdrawNormalBrokerageAmount(0);
		BigDecimal crowdsourceBrokerageAmount = partnerBrokerageMapper.getTotalCrowdsourceBrokerageByCompid(0);
		BigDecimal allBalanceAmount = companyPaymentMapper.getAllCompanyBalanceSum();
//		BigDecimal alipayBalance = companyAccountMapper.getAlipayBalanceSum();
		//		//查询得仕九歌余额
		//		BigDecimal balanceOne = balanceService.queryDeShiJiuGeBalance();
		//		//查询得仕武圣余额
		//		BigDecimal balanceTwo = balanceService.queryDeShiWuShengBalance();
		//查询传化武圣余额
		// BigDecimal balanceThree = balanceService.queryChuanHuaWuShengBalance();
		//		//查询得仕智圣余额
		//		BigDecimal balanceFour = balanceService.queryDeShiZhiShengBalance();
		//		//查询得仕信圣余额
		//		BigDecimal balanceFive = balanceService.queryDeShiXinShengBalance();
		//查询传化信圣余额
		//		BigDecimal balanceSix = balanceService.queryChuanHuaXinShengBalance();
		//		//查询得仕英圣余额
		//		BigDecimal balanceSeven = balanceService.queryDeShiYingShengBalance();
		//查询招商九歌余额
		BigDecimal balanceEight = balanceService.queryZhaoShangJiuGeBalance();
		//查询招商信圣余额
		BigDecimal balanceNine = balanceService.queryZhaoShangXinShengBalance();
		//查询招商智圣余额
		BigDecimal balanceTen = balanceService.queryZhaoShangZhiShengBalance();
//		//查询招商法圣余额
//		BigDecimal balanceEleven = balanceService.queryZhaoShangFaShengBalance();
		//查询招商明圣余额
		BigDecimal balanceMing = balanceService.queryZhaoShangBalance(14);
		//查询传化智圣余额
		//		BigDecimal bigDecimalZhiSheng = balanceService.queryChuanHuaZhiShengBalance();
		//查询传化九歌
		//		BigDecimal bigDecimalJiuGe = balanceService.queryChuanHuaJiuGeBalance();
		//查询招商秀圣余额
		BigDecimal xiuShengBalance = balanceService.queryZhaoShangBalance(15);
		//查询招商美余额
		BigDecimal meiShengBalance = balanceService.queryZhaoShangBalance(16);
		//查询招商美余额
		BigDecimal yingShengBalance = balanceService.queryZhaoShangBalance(17);
		//查询招商如山余额
		BigDecimal ruShanBalance = balanceService.queryZhaoShangBalance(19);
		//查询招商河南冉澄余额
		BigDecimal ranChengBalance = BigDecimal.ZERO;// balanceService.queryZhaoShangBalance(20);
		//查询招商宁夏如火余额
		BigDecimal ruHuoBalance = balanceService.queryZhaoShangBalance(21);
		//查询招商青岛如风余额
		BigDecimal ruFengBalance = balanceService.queryZhaoShangBalance(22);

		return smartResult(new CompanyAccountStatisticDto(unsettledProjectAmount, unwithDrawBrokerageAmount, crowdsourceBrokerageAmount,
				allBalanceAmount, BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO,
				BigDecimal.ZERO, BigDecimal.ZERO, balanceEight, balanceNine, balanceTen, BigDecimal.ZERO, balanceMing, xiuShengBalance,
				meiShengBalance, yingShengBalance, BigDecimal.ZERO, BigDecimal.ZERO,ruShanBalance,ranChengBalance, BigDecimal.ZERO,ruHuoBalance,ruFengBalance));
	}

	public SmartResult<CompanyCommissionStatisticDto> allCompanyAccountNoCommission(BaseSimpleFormBean formBean) {
		CompanyCommissionStatisticDto statisticDto = new CompanyCommissionStatisticDto();
		BigDecimal amount = partnerBrokerageMapper.getUnTurnoverCommissionAmount(2, 3, 2);
		statisticDto.setUnTurnoverCommission(amount);

		BigDecimal decimal = partnerMonthlyCrowdCostMapper.getUnCostCommissionAmount(PartnerCrowdsourceCostState.UNSETTLED);
		statisticDto.setUnCostCommission(decimal);

		return smartResult(statisticDto);
	}

	/**
	 * 获取创客账户流水
	 */
	public SmartResult getUserAccountFlow(BaseSimpleFormBean<UserAccountFlowFormBean> formBean) {
		UserAccountFlowFormBean reqdata = formBean.getReqdata();
		if (reqdata == null) return errorParamSmartResult();

		String name = reqdata.getName();
		int flowtype = reqdata.getFlowtype();
		Date startDate = reqdata.getStartDate();
		Date endDate = reqdata.getEndDate();

		if (startDate == null) startDate = new Date(0);
		if (endDate == null) endDate = new Date();

		Page<Object> page = PageHelper.startPage(formBean.getPage(), formBean.getRows());
		makerAccountflowMapper.getAccountFlowList(name, flowtype, startDate, endDate);

		return smartResultPage(page);
	}

	/**
	 * 获取代付列表
	 */
	public void downloadTradeRecord(HttpServletResponse response, TradeRecordListFormBean reqdata) {
		if (reqdata == null) ;

		String name = reqdata.getName();
		Date startDate = reqdata.getStartDate();
		Date endDate = reqdata.getEndDate();
		int tradetype = reqdata.getTradetype();
		//交易状态 1:创建中 2:处理中 3:交易成功 4:交易失败 5:交易拒绝
		int tradestate = reqdata.getTradestate();

		if (startDate == null) startDate = new Date(0);
		if (endDate == null) endDate = new Date();

		List<TradeRecordBriefDto> list = tradeRecordMapper.getTradeRecordList(name, tradetype, tradestate, startDate, endDate);
		String file = RandomUtil.createRandomNo("代付账目_", "");

		EasyExcelUtil.download(response, file, TradeRecordBriefDto.class, list);
	}

	public void downloadCompAcctFlow(HttpServletResponse response, CompanyAccountFlowFormBean reqdata) {

		String name = reqdata.getName();
		int flowtype = reqdata.getFlowtype();
		Date startDate = reqdata.getStartDate();
		Date endDate = reqdata.getEndDate();

		if (startDate == null) startDate = new Date(0);
		if (endDate == null) endDate = new Date();

		List<CompanyAccountFlowDto> list = companyAccountflowMapper.getAccountFlowList(name, flowtype, reqdata.getAccountType(), startDate,
				endDate);
		if (CollectionUtils.isNotEmpty(list)) {
			for (CompanyAccountFlowDto flow : list) {
				if (flow.getBizType() == CompanyAccountFlowBizType.ZDD_PROJECT) {
					CompanyProject companyAccount = companyAccountflowMapper.getMakerLedger(flow.getBizid());
					if (companyAccount != null) {
						flow.setRealname(companyAccount.getRealname()).setUsername(companyAccount.getUsername());
					}
				} else if (NumberUtil.intIn(flow.getBizType(),CompanyAccountFlowBizType.CROWDSOURCE_PROJECT,CompanyAccountFlowBizType.CROWDSOURCE_ODD_PROJECT)) {
					List<CrowdsourcingLedgerDto> dtos = companyAccountflowMapper.getCrowdsourcingLedger(flow.getBizid());
					flow.setRealname(
							StringUtils.join(dtos.stream().map(CrowdsourcingLedgerDto::getRealname).collect(Collectors.toSet()), ","));
					flow.setUsername(
							StringUtils.join(dtos.stream().map(CrowdsourcingLedgerDto::getUsername).collect(Collectors.toSet()), ","));
				} else if (flow.getBizType() == CompanyAccountFlowBizType.GROUPON_PROJECT) {
					CrowdsourcingLedgerDto dto = companyAccountflowMapper.getGroupMakerByBizId(flow.getBizid(), flow.getItemId());
					flow.setRealname(dto.getRealname()).setUsername(dto.getUsername());
				} else if (flow.getBizType() == CompanyAccountFlowBizType.ENTRUST_PROJECT) {
					CrowdsourcingLedgerDto dto = companyAccountflowMapper.getEntrustmentByBizId(flow.getBizid(), flow.getItemId());
					flow.setRealname(dto.getRealname()).setUsername(dto.getUsername());
				}
			}
		}
		String file = RandomUtil.createRandomNo(name + "_企业账户流水_", "");
		EasyExcelUtil.download(response, file, CompanyAccountFlowDto.class, list);
	}

	public void downloadStudioAcctFlow(HttpServletResponse response, UserAccountFlowFormBean reqdata) {

		String name = reqdata.getName();
		int flowtype = reqdata.getFlowtype();
		Date startDate = reqdata.getStartDate();
		Date endDate = reqdata.getEndDate();

		if (startDate == null) startDate = new Date(0);
		if (endDate == null) endDate = new Date();

		List<MakerAccountFlowDto> list = makerAccountflowMapper.getAccountFlowList(name, flowtype, startDate, endDate);
		String file = RandomUtil.createRandomNo(name + "_工作室账户流水_", "");

		EasyExcelUtil.download(response, file, MakerAccountFlowDto.class, list);
	}

	public SmartResult<QuarterBusinessGrossDto> getBusinessGrossList(BaseSimpleFormBean<Integer> formBean) {
		@Valid Integer year = formBean.getReqdata();
		if (year == null) year = DateUtil.getNowYear();

		String json = redisService.getString(RedisKey.genQuarterBusinessGrossKey(year));

		List<QuarterBusinessGrossDto> list;
		if (StringUtil.isEmpty(json)) {
			// list = calcQuarterBusinessGross(year);
			list = Lists.newArrayList();
		} else {
			list = JSON.parseArray(json, QuarterBusinessGrossDto.class);
		}
		return SmartResult.success(list);

	}

	public SmartResult<MonthBusinessGross> getBusinessMonthGrossList(BaseSimpleFormBean<Integer> formBean) {
		@Valid Integer year = formBean.getReqdata();
		if (year == null) year = DateUtil.getNowYear();

		List<MonthBusinessGross> list = monthBusinessGrossMapper.listByYear(year);
		return SmartResult.success(list);

	}

	/**
	 * 定时任务, 计算季度利润统计
	 */
	public void calcQuarterBusinessGrossJob() {
		int startYear = 2019;// 业务开始的年份
		int currYear = DateUtil.getNowYear();
		for (int i = startYear; i <= currYear; i++) {
			calcQuarterBusinessGross(i);

		}
	}

	/**
	 * 定时任务, 计算月度利润统计
	 */
	public void calcMonthBusinessGrossJob(Date from, Date to) {
		// 默认到这个月
		if (to == null) to = DateUtil.getThisMonthBeginDate();
		// 如果没有from, 默认从前一个季度开始统计
		if (from == null) {
			Date quarterBeginDate = DateUtil.getQuarterBeginDate(to);
			from = DateUtil.addMonth(quarterBeginDate, -3);
		}

		// 所有有效的创客id
		List<Integer> validMakerIds = makerMapper.getValidMakerIds();
		// 循环计算每月数据，直到当前月份
		Date currDate = from;
		while (currDate.before(to) || currDate.equals(to)) {
			int currYear = DateUtil.getYear(currDate);
			int currMonth = DateUtil.getMonth(currDate);
			calcMonthBusinessGross(validMakerIds, currYear, currMonth);
			// 下一个月
			currDate = DateUtil.addMonth(currDate, 1);
		}

	}

	public List<QuarterBusinessGrossDto> calcQuarterBusinessGross(int year) {
		List<Integer> validMakerIds = makerMapper.getValidMakerIds();
		ArrayList<QuarterBusinessGrossDto> list = Lists.newArrayList();
		for (int i = 1; i <= 4; i++) {
			list.add(genGross(validMakerIds, year, i));
		}

		// 保存2天
		redisService.set(RedisKey.genQuarterBusinessGrossKey(year), JSON.toJSONString(list), 60 * 60 * 24 * 2);

		return list;
	}

	public void calcMonthBusinessGross(List<Integer> validMakerIds, int year, int month) {
		MonthBusinessGross monthBusinessGross = genMonthGross(validMakerIds, year, month);
		MonthBusinessGross oldMonthBusinessGross = monthBusinessGrossMapper.getByYearMonth(year, month);
		if (oldMonthBusinessGross != null) {
			// 将新计算出来的值复制给老的数据上
			oldMonthBusinessGross.copy(monthBusinessGross);
			oldMonthBusinessGross.updateById();
		} else {
			monthBusinessGross.insert();
		}
		log.info("calcMonthBusinessGross, 完成：{} - {}", year, month);
	}

	private QuarterBusinessGrossDto genGross(List<Integer> validMakerIds, int year, int quarter) {
		//业务收入= 每个项目的服务费
		//30万以内 税金成本普票1% . 增值税 0
		//30万 75万以上 税金成本 0, 增值税也是4.46%
		//合伙人佣金 = 项目成交成交价 *  0.8%

		// 新逻辑
		// 服务费固定项目款2%
		// 个税按年度总金额 档次, 每个季度分别用当前季度的 总金额*年度的档次比例
		// 季度30万以内, 普票增值税0, 专票按3.36
		// 毛利:服务费-合伙人佣金

		QuarterBusinessGrossDto quarterBusinessGrossDto = validMakerIds.parallelStream().map(userid -> {
			MakerDetailDto userDetail = makerMapper.getUserDetail(userid);
			//当前季度总金额
			BigDecimal quarterTotalAmount = coreProjectService.getUserQuarterTotalAmountByYearQuarter(userid, CalcAmountType.CHECKED, year,
					quarter);
			//年度总金额
			BigDecimal yearlyTotalAmount = coreProjectService.getUserYearlyTotalAmount(userid, CalcAmountType.CHECKED, year);

			// 服务费
			BigDecimal serviceCharge;
			// 个税
			BigDecimal taxFee;
			// 增值税
			BigDecimal valueAddedTax;

			//服务费固定项目款2%
			// BigDecimal serviceCharge = coreProjectService.getUserQuarterServiceCharge(userid, 2, year, quarter);
			serviceCharge = quarterTotalAmount.multiply(BigDecimal.valueOf(0.02));

			// 个税 (当前季度总金额 * 年度总金额的档次比例)
			if (userDetail.getMakerType() == MakerType.CROWDSOURCE && userDetail.getOpeningLocation() == 3) {
				// 智众包的芜湖集群注册（来源是智众包的芜湖创客）按季度30万成本为0，超出30万按2.6
				if (quarterTotalAmount.doubleValue() > 300000) {
					taxFee = quarterTotalAmount.multiply(BigDecimal.valueOf(0.026));
				} else {
					taxFee = BigDecimal.ZERO;
				}
			} else {
				if (yearlyTotalAmount.doubleValue() <= commonConfig.getYearlyHighAmount()) {
					// 75以下: 1%
					taxFee = quarterTotalAmount.multiply(BigDecimal.valueOf(0.01));
				} else if (yearlyTotalAmount.doubleValue() <= commonConfig.getYearlyHigh2Amount()) {
					// 75以上: 2%
					taxFee = quarterTotalAmount.multiply(BigDecimal.valueOf(0.02));
				} else if (yearlyTotalAmount.doubleValue() <= commonConfig.getYearlyHigh3Amount()) {
					// 150以上: 2.1%
					taxFee = quarterTotalAmount.multiply(BigDecimal.valueOf(0.021));
				} else {
					// 300以上: 2.6%
					taxFee = quarterTotalAmount.multiply(BigDecimal.valueOf(0.026));
				}
			}

			// 增值税, 年度不超过75万,季度不超过30万,普票增值税为0, 专票3.36. 季度超过30万或年度超过75万,普票专票都按3.36
			if (yearlyTotalAmount.doubleValue() <= commonConfig.getYearlyHighAmount() &&
					quarterTotalAmount.doubleValue() <= commonConfig.getGenQuarterSplitAmount()) {
				BigDecimal genTotalAmount = coreProjectService.getUserQuarterGenTotalAmountByYearQuarter(userid, CalcAmountType.CHECKED,
						year, quarter);
				BigDecimal specialAmount = quarterTotalAmount.subtract(genTotalAmount);
				if (specialAmount.doubleValue() <= 0) specialAmount = BigDecimal.ZERO;
				valueAddedTax = specialAmount.multiply(BigDecimal.valueOf(0.0336));
			} else {
				valueAddedTax = quarterTotalAmount.multiply(BigDecimal.valueOf(0.0336));
			}

			// 合计
			BigDecimal sum = serviceCharge.add(taxFee).add(valueAddedTax);

			return new QuarterBusinessGrossDto().setYear(year)
					.setQuarter(quarter)
					.setQuarterTotalAmount(quarterTotalAmount)
					.setServiceCharge(serviceCharge)
					.setTaxFee(taxFee)
					.setValueAddedTax(valueAddedTax)
					.setSum(sum);

		}).reduce(QuarterBusinessGrossDto::add).orElse(QuarterBusinessGrossDto.of(year, quarter));

		// 自然人总的项目金额，只计算服务费，税费肯定不会超过季度限额。
		BigDecimal serviceCharge = quarterBusinessGrossDto.getServiceCharge();
		BigDecimal naturalPersonQuarterAmount = crowdsourceProjectItemMapper.getQuarterTotalIntegratedAmountByStates(0,
				CrowdsourceUserType.NATURAL_PERSON, 0, CalcAmountType.getCrowdsourceProjectStates(CalcAmountType.CHECKED), year, quarter);
		BigDecimal naturalPersonServiceCharge = naturalPersonQuarterAmount.multiply(BigDecimal.valueOf(0.02));
		serviceCharge = serviceCharge.add(naturalPersonServiceCharge);

		// 合伙人佣金
		BigDecimal totalBrokerage = partnerBrokerageMapper.getTotalBrokerageByQuarter(year, quarter);
		BigDecimal brokerage = totalBrokerage.multiply(BigDecimal.valueOf(0.008));

		// 毛利 = 服务费-合伙人佣金
		BigDecimal gross = serviceCharge.subtract(brokerage);
		quarterBusinessGrossDto.setServiceCharge(serviceCharge).setBrokerage(brokerage).setGross(gross);

		return quarterBusinessGrossDto;
	}

	private MonthBusinessGross genMonthGross(List<Integer> validMakerIds, int year, int month) {
		try {
			//业务收入= 每个项目的服务费
			//30万以内 税金成本普票1% . 增值税 0
			//30万 75万以上 税金成本 0, 增值税也是4.46%
			//合伙人佣金 = 项目成交成交价 *  0.8%

			// 新逻辑
			// 服务费固定项目款2%
			// 个税按年度总金额 档次, 每个季度分别用当前季度的 总金额*年度的档次比例
			// 季度30万以内, 普票增值税0, 专票按3.36
			// 毛利:服务费-合伙人佣金

			int calcAmountType = CalcAmountType.CHECKED;
			int quarter = DateUtil.getQuarterOfMonth(month);
			MonthBusinessGross monthBusinessGross = validMakerIds.parallelStream().map(userid -> {
				try {
					MakerDetailDto userDetail = makerMapper.getUserDetail(userid);
					// 当前月份总金额
					BigDecimal monthTotalAmount = coreProjectService.getUserMonthlyTotalAmountByYearMonth(userid, calcAmountType, year,
							month);
					//当前季度总金额
					BigDecimal quarterTotalAmount = coreProjectService.getUserQuarterTotalAmountByYearQuarter(userid, calcAmountType, year,
							quarter);
					//年度总金额
					BigDecimal yearlyTotalAmount = coreProjectService.getUserYearlyTotalAmount(userid, calcAmountType, year);

					// 服务费
					BigDecimal serviceCharge = BigDecimal.ZERO;
					// 个税
					BigDecimal taxFee = BigDecimal.ZERO;
					// 增值税
					BigDecimal valueAddedTax = BigDecimal.ZERO;

					//服务费固定项目款2%
					serviceCharge = monthTotalAmount.multiply(BigDecimal.valueOf(0.02));

					// 个税 (当前季度总金额 * 年度总金额的档次比例)
					if (userDetail.getMakerType() == MakerType.CROWDSOURCE && userDetail.getOpeningLocation() == 3) {
						// 智众包的芜湖集群注册（来源是智众包的芜湖创客）按季度30万成本为0，超出30万按2.6
						if (quarterTotalAmount.doubleValue() > 300000) {
							taxFee = monthTotalAmount.multiply(BigDecimal.valueOf(0.026));
						} else {
							taxFee = BigDecimal.ZERO;
						}
					} else {
						if (yearlyTotalAmount.doubleValue() <= commonConfig.getYearlyHighAmount()) {
							// 75以下: 1%
							taxFee = monthTotalAmount.multiply(BigDecimal.valueOf(0.01));
						} else if (yearlyTotalAmount.doubleValue() <= commonConfig.getYearlyHigh2Amount()) {
							// 75以上: 2%
							taxFee = monthTotalAmount.multiply(BigDecimal.valueOf(0.02));
						} else if (yearlyTotalAmount.doubleValue() <= commonConfig.getYearlyHigh3Amount()) {
							// 150以上: 2.1%
							taxFee = monthTotalAmount.multiply(BigDecimal.valueOf(0.021));
						} else {
							// 300以上: 2.6%
							taxFee = monthTotalAmount.multiply(BigDecimal.valueOf(0.026));
						}
					}

					// 增值税, 年度不超过75万,季度不超过30万,普票增值税为0, 专票3.36. 季度超过30万或年度超过75万,普票专票都按3.36
					if (yearlyTotalAmount.doubleValue() <= commonConfig.getYearlyHighAmount() &&
							quarterTotalAmount.doubleValue() <= commonConfig.getGenQuarterSplitAmount()) {
						// 月度普票金额
						BigDecimal monthGenTotalAmount = coreProjectService.getUserMonthlyGenTotalAmount(userid, calcAmountType, 0, 0,
								year,
								month, true, true);
						BigDecimal specialAmount = monthTotalAmount.subtract(monthGenTotalAmount);
						if (specialAmount.doubleValue() <= 0) specialAmount = BigDecimal.ZERO;
						valueAddedTax = specialAmount.multiply(BigDecimal.valueOf(0.0336));
					} else {
						valueAddedTax = monthTotalAmount.multiply(BigDecimal.valueOf(0.0336));
					}

					// 合计
					BigDecimal sum = serviceCharge.add(taxFee).add(valueAddedTax);

					return new MonthBusinessGross().setYear(year)
							.setQuarter(quarter)
							.setMonth(month)
							.setServiceCharge(serviceCharge)
							.setTaxFee(taxFee)
							.setValueAddedTax(valueAddedTax)
							.setSum(sum);
				} catch (Exception e) {
					log.error("genMonthGross {} - {}， userid:{} 报错", year, month, userid, e);
					return MonthBusinessGross.of(year, month);
				}
			}).reduce(MonthBusinessGross::add).orElse(MonthBusinessGross.of(year, month));

			//  交易额
			BigDecimal zhiduoduoAmount = projectMapper.getMonthTotalAmountByStates(0, 0, 0,
					CalcAmountType.getZhiduoduoProjectStates(calcAmountType), year, month);
			// 智众包交易额
			BigDecimal crowdsourceAmount = crowdsourceProjectItemMapper.getMonthlyTotalIntegratedAmountByStates(0,
					CrowdsourceUserType.STUDIO, 0, CalcAmountType.getCrowdsourceProjectStates(calcAmountType), year, month);
			//  交易额
			BigDecimal taxerAmount = taxerInvoiceMapper.getMonthTaxerTotalAmount(0, 0, year, month);
			// 纯代理交易额
			BigDecimal agentTaxerAmount = taxerInvoiceMapper.getMonthAgentTaxerTotalAmount(0, 0, year, month);
			// 委托接单交易额
			BigDecimal entrustAmount = entrustmentProjectItemMapper.sumUserMonthTotalEntrustProjectAmountByStates(0,
					CalcAmountType.getEntrustProjectStates(calcAmountType), year, month);
			// 创客团交易额
			BigDecimal grouponAmount = entrustmentProjectItemMapper.sumUserMonthTotalMakerGrouponProjectAmountByStates(0,
					CalcAmountType.getEntrustProjectStates(calcAmountType), year, month);
			// 月度小计
			BigDecimal monthAmount = zhiduoduoAmount.add(crowdsourceAmount)
					.add(taxerAmount)
					.add(agentTaxerAmount)
					.add(entrustAmount)
					.add(grouponAmount);

			// 自然人总的项目金额，只计算服务费，税费肯定不会超过季度限额。
			BigDecimal serviceCharge = monthBusinessGross.getServiceCharge();
			BigDecimal naturalPersonQuarterAmount = crowdsourceProjectItemMapper.getMonthlyTotalIntegratedAmountByStates(0,
					CrowdsourceUserType.NATURAL_PERSON, 0, CalcAmountType.getCrowdsourceProjectStates(CalcAmountType.CHECKED), year,
					month);
			BigDecimal naturalPersonServiceCharge = naturalPersonQuarterAmount.multiply(BigDecimal.valueOf(0.02));
			serviceCharge = serviceCharge.add(naturalPersonServiceCharge);

			// 合伙人佣金
			BigDecimal totalBrokerage = partnerBrokerageMapper.getTotalBrokerageByMonth(year, month);
			BigDecimal brokerage = totalBrokerage.multiply(BigDecimal.valueOf(0.008));

			// 毛利 = 服务费-合伙人佣金
			BigDecimal gross = serviceCharge.subtract(brokerage);
			monthBusinessGross.setZddAmount(zhiduoduoAmount)
					.setCrowdsourceAmount(crowdsourceAmount)
					.setTaxerAmount(taxerAmount)
					.setAgentTaxerAmount(agentTaxerAmount)
					.setEntrustAmount(entrustAmount)
					.setMakerGrouponAmount(grouponAmount)
					.setMonthAmount(monthAmount)
					.setServiceCharge(serviceCharge)
					.setBrokerage(brokerage)
					.setGross(gross);

			return monthBusinessGross;
		} catch (Exception e) {
			log.error("计算月度利润报错", e);
			throw e;
		}
	}

	public void downloadQuarterStudioList(int year, int quarter, HttpServletResponse response) {
		List<ExportQuarterStudioDto> list = companyProjectMapper.getQuarterStudioList(year, quarter);
		String filename = "季度大于30万的创客";
		EasyExcelUtil.download(response, filename, ExportQuarterStudioDto.class, list);

	}

//	public SmartResult<CompanyOfflineRechargeDto> getOfflineRechargeOrderList(
//			BaseSimpleFormBean<OfflineRechargeOrderListFormBean> formBean) {
//		@Valid OfflineRechargeOrderListFormBean reqdata = formBean.getReqdata();
//		String rechargeNo = reqdata.getRechargeNo();
//		Date startDate = reqdata.getStartDate();
//		Date endDate = reqdata.getEndDate();
//		int state = reqdata.getState();
//
//		if (startDate == null) startDate = DateUtil.getEpochTime();
//		if (endDate == null) endDate = new Date();
//
//		Page<CompanyOfflineRechargeDto> page = PageHelper.startPage(formBean.getPage(), formBean.getRows());
//		companyOfflineRechargeMapper.findOrderList(0, rechargeNo, state, startDate, endDate);
//		return SmartResult.ofPage(page);
//	}
//
//	public SmartResult<CompanyOfflineRechargeDetailDto> getOfflineRechargeOrderDetail(BaseSimpleFormBean<Integer> formBean) {
//		List<CompanyOfflineRechargeDetailDto> detailList = companyOfflineRechargeDetailMapper.findDetailList(formBean.getReqdata());
//		return SmartResult.success(detailList);
//	}
//
//	/**
//	 * 发送充值验证码,微信模板消息
//	 */
//	public SmartResult sendOfflineRechargeVerifyCode(BaseSimpleFormBean<Integer> formBean) {
//		Integer rechargeDetailId = formBean.getReqdata();
//		if (rechargeDetailId == null || rechargeDetailId <= 0) return errorParamSmartResult();
//
//		//发送验证码
//		String verifycode = RandomUtil.getRandomNum(4);
//		String key = RedisKey.genOfflineVerifyCodeKey(rechargeDetailId);
//		redisService.set(key, verifycode, 10 * 60);
//
//		//发送验证码模板消息
//		wxMessageService.sendOfflineVerifycode(rechargeDetailId, verifycode);
//		return smartResult();
//	}
//
//	public SmartResult rechargeTransferedAmount(BaseSimpleFormBean<RechargeTransferedAmountFormBean> formBean) {
//
//		@Valid RechargeTransferedAmountFormBean reqdata = formBean.getReqdata();
//		int id = reqdata.getId();
//		String verifycode = reqdata.getVerifycode();
//
//		CompanyOfflineRechargeDetail rechargeDetail = new CompanyOfflineRechargeDetail().selectById(id);
//		if (rechargeDetail == null) return SmartResult.fail(StatusMsg.StatusMsg_320);
//
//		CompanyOfflineRechargeDto recharge = companyOfflineRechargeMapper.findById(rechargeDetail.getOfflineRechargeId());
//		if (recharge == null) return SmartResult.fail(StatusMsg.StatusMsg_320);
//
//		//判断验证码正确或是否超时,  测试环境使用0000
//		if (!"0000".equals(verifycode)) {
//			String savedCode = redisService.getString(RedisKey.genOfflineVerifyCodeKey(id));
//
//			if (StringUtil.isEmpty(savedCode)) {
//				return smartResult(StatusMsg.StatusMsg_112);
//			} else if (!savedCode.equals(verifycode)) {
//				return smartResult(StatusMsg.StatusMsg_106);
//			}
//		}
//
//		boolean update = rechargeDetail.setState(2).setRechargeTime(new Date()).updateById();
//		if (update) {
//			BigDecimal amount = rechargeDetail.getAmount();
//			CompanyAccount account = new CompanyAccount().selectOne(Condition.create().eq("compid", recharge.getCompid()));
//			BigDecimal beforeBalance = account.getBalance();
//			BigDecimal currBalance = beforeBalance.add(amount);
//			account.setBalance(currBalance);
//			boolean accountUpdate = companyAccountMapper.updateById(account) > 0;
//
//			if (accountUpdate) {
//				//确认完成,生成企业流水
//				boolean insertFLow = new CompanyAccountflow().setCompid(recharge.getCompid())
//						.setFlowAmount(amount)
//						.setBeforeBalance(beforeBalance)
//						.setCurrBalance(currBalance)
//						.setBizid(recharge.getId())
//						.setBizType(CompanyAccountFlowBizType.RECHARGE)
//						.setFlowtype(1)
//						.setFlowname(Constants.ACCT_FLOW_OFFLINE_RECHARGE)
//						.insert();
//
//				// 判度充值是否完成
//				boolean rechargeCompleted = recharge.getRechargedAmount().add(amount).compareTo(recharge.getAmount()) >= 0;
//				if (rechargeCompleted) {
//					new CompanyOfflineRecharge().setState(Constants.OFFLINE_RECHARGE_COMPLETED);
//				}
//				if (insertFLow) {
//					wxMessageService.notifyCompanyOfflineRecharged(rechargeDetail);
//					return smartResult();
//				} else {
//					log.info("生成企业流水失败-->回滚");
//					//手动回滚
//					TransactionUtil.setRollbackOnly();
//				}
//			} else {
//				log.info("企业账户余额更新失败-->回滚");
//				//手动回滚
//				TransactionUtil.setRollbackOnly();
//			}
//		}
//		// 失败回滚
//		return SmartResult.ofOptFail();
//	}

	public void checkOfflineRechargeOrder() {

		new CompanyOfflineRecharge().setState(Constants.OFFLINE_RECHARGE_TRANSFER_FINISHED)
				.update(Condition.create().le("state", Constants.OFFLINE_RECHARGE_TRANSFERING).lt("closetime", new Date()));

	}

	/**
	 * 统计创客从开户日期算，12个月交易额未达到10万的创客列表
	 *
	 * @param formBean formBean
	 * @return NotUpStandardMakerDto
	 */
	public SmartResult<NotUpStandardMakerDto> notUpStandardMakerList(BaseSimpleFormBean<NotUpStandardMakerFormBean> formBean) {
		NotUpStandardMakerFormBean reqdata = formBean.getReqdata();
		// 增加 待处理 已处理 状态筛选
		int state = 0;
		if (reqdata.getType() == 1) {
			state = 1;
		}
		Integer special = reqdata.getSpecial();
		if (special == null) {
			special = 0;
		}
		Page<Object> page = PageHelper.startPage(formBean.getPage(), formBean.getRows());
		List<NotUpStandardMakerDto> list = makerMapper.notUpStandardMakerList(reqdata.getName(), state, special);
		//返回免费年限
		Map<Integer,PlatformMemorandum> companyMap = new HashMap<>();
		Map<Integer,PlatformMemorandum> userStudioMap = new HashMap<>();
		List<PlatformMemorandum> companyStudioList = makerStudioMapper.queryStudioByCompany();
		List<PlatformMemorandum> userStudioList = makerStudioMapper.queryStudioByUserIds();
		if (CollectionUtils.isNotEmpty(companyStudioList)) {
			for (PlatformMemorandum dto:companyStudioList){
				companyMap.put(dto.getCustomerId(),dto);
			}
		}
		if (CollectionUtils.isNotEmpty(userStudioList)) {
			for (PlatformMemorandum dto:userStudioList){
				userStudioMap.put(dto.getCustomerId(),dto);
			}
		}
		for (NotUpStandardMakerDto dto:list){
			int freeYears = 0;
			if (userStudioMap.containsKey(dto.getUserid())){
				if (userStudioMap.get(dto.getUserid()).getFreeType() == 2){
					freeYears = platformMemorandumMapper.getFreeYears(dto.getUserid(),1);
				}
			}else {
				if (companyMap.containsKey(dto.getBindcompid())){
					if (companyMap.get(dto.getBindcompid()).getFreeType() == 2){
						freeYears = platformMemorandumMapper.getFreeYears(dto.getBindcompid(),2);
					}
				}
			}
			dto.setFreeYears(freeYears);
		}
		return smartResult(list, page.getTotal(), page.getPages(), page.getPageNum());
	}

	/**
	 * 统计创客从开户日期算，12个月交易额未达到10万的创客列表（导出）
	 *
	 * @param response
	 * @param name
	 * @param type
	 */
	public void notUpStandardMakerListImportExcel(HttpServletResponse response, String name, Integer type) {
		// 增加 待处理 已处理 状态筛选
		int state = 1;
		if (type == null || type.equals(0)) {
			state = 0;
		}
		List<NotUpStandardMakerExcelDto> list = makerMapper.notUpStandardMakerExcelList(name, state, 0);

		list.stream().forEach(x -> x.setTotalAmount(makerMapper.notUpStandardMakerDetailExcel(x.getUserid())));

		String file = RandomUtil.createRandomNo("创客交易未满10万", "");
		try {
			EasyExcel.write(getExcelOutPutStream(response, file), NotUpStandardMakerExcelDto.class).sheet("创客详情").doWrite(list);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**
	 * 下载统计创客从开户日期算，12个月交易额未达到10万的创客列表
	 */
	public void downloadNotUpStandardMakerList(HttpServletResponse response, NotUpStandardMakerFormBean reqdata) {
		// 增加 待处理 已处理 状态筛选
		int state = 0;
		if (reqdata.getType() == 1) {
			state = 1;
		}
		Integer special = reqdata.getSpecial();
		if (special == null) {
			special = 0;
		}
		List<NotUpStandardMakerDto> list = makerMapper.notUpStandardMakerList(reqdata.getName(), state, special);
		EasyExcelUtil.download(response, "12个月交易额未达到10万的创客列表", NotUpStandardMakerDto.class, list);
	}

	/**
	 * 查看 12个月交易额未达到10万的创客 的详情
	 *
	 * @param formBean
	 * @return
	 */
	public SmartResult<NotUpStandardDetailDto> notUpStandardMakerDetail(BaseSimpleFormBean<Integer> formBean) {

		Integer userid = formBean.getReqdata();
		List<NotUpStandardDetailDto> list = makerMapper.notUpStandardMakerDetail(userid);
		return smartResult(list);
	}

	/**
	 * 获取指定年份每月 交易额及总税费
	 *
	 * @param formBean
	 * @return
	 */
	public SmartResult<MonthZhiduoTradingVolumeDto> getZhiduoTradingVolumeList(BaseSimpleFormBean<Integer> formBean) {
		@Valid Integer year = formBean.getReqdata();
		if (year == null) {
			year = DateUtil.getNowYear();
		}
		//以月份分组获取  交易额及总税费
		List<MonthZhiduoTradingVolumeDto> list = companyProjectMapper.getZhiduoTradingVolumeListGroupByMonth(year);
		return SmartResult.success(list);
	}

	/**
	 * 获取指定年份每月 交易额及总税费
	 *
	 * @param formBean
	 * @return
	 */
	public SmartResult<MonthZhiduoTradingVolumeDto> getTaxerTradingVolumeList(BaseSimpleFormBean<Integer> formBean) {
		@Valid Integer year = formBean.getReqdata();
		if (year == null) {
			year = DateUtil.getNowYear();
		}
		//以月份分组获取  交易额及总税费
		List<MonthZhiduoTradingVolumeDto> list = taxerInvoiceMapper.getTaxerTradingVolumeList(year);
		return SmartResult.success(list);
	}

	/**
	 * 获取指定年份每月 交易额及总税费
	 *
	 * @param formBean
	 * @return
	 */
	public SmartResult<MonthZhiduoTradingVolumeDto> getPureAgencyTradingVolumeList(BaseSimpleFormBean<Integer> formBean) {
		@Valid Integer year = formBean.getReqdata();
		if (year == null) {
			year = DateUtil.getNowYear();
		}
		//以月份分组获取  交易额及总税费
		List<MonthZhiduoTradingVolumeDto> list = taxerInvoiceMapper.getPureAgencyTradingVolumeList(year);
		return SmartResult.success(list);
	}

	/**
	 * 获取指定年份每月智众包交易额及总税费
	 *
	 * @param formBean
	 * @return
	 */
	public SmartResult<MonthCrowdSourceTradingVolumeDto> getCrowdSourceTradingVolumeList(BaseSimpleFormBean<Integer> formBean) {
		@Valid Integer year = formBean.getReqdata();
		if (year == null) {
			year = DateUtil.getNowYear();
		}
		//以月份分组获取 智众包交易额及总税费
		List<MonthCrowdSourceTradingVolumeDto> list = crowdsourceProjectMapper.getCrowdSourceTradingVolumeList(year);
		return SmartResult.success(list);
	}

	/**
	 * 保存 处理结果
	 *
	 * @param baseSimpleFormBean
	 * @return
	 */
	@Transactional
	public SmartResult saveHandleRecord(BaseSimpleFormBean<SaveHandleRecordFormBean> baseSimpleFormBean) {

		SaveHandleRecordFormBean formBean = baseSimpleFormBean.getReqdata();

		MakerHandle makerHandle = new MakerHandle();
		BeanUtils.copyProperties(formBean, makerHandle);
		makerHandle.setCreatetime(new Date());
		makerHandle.setUpdatetime(new Date());

		if (!makerHandle.insert()) return optFailSmartResult();

		// 修改为 已处理
		MakerCycleRecord cycleRecord = new MakerCycleRecord().selectOne(
				Condition.create().eq("userid", makerHandle.getUserid()).eq("year_mark", makerHandle.getHandleYear()));
		if (cycleRecord != null) {
			cycleRecord.setState(1);
			cycleRecord.updateById();
		}
		//处理注销
		if (4 == formBean.getHandleType()) {
			List<MakerRescissionApply> repeat = new MakerRescissionApply().selectList(Condition.create().eq("userid",formBean.getUserid()).ne("state",3));
			if ( repeat.size() <= 0 ) {
				MakerRescissionApply apply = new MakerRescissionApply();
				apply.setUserid(formBean.getUserid())
						.setHandleAdminid(baseSimpleFormBean.getUserid())
						.setState(1)
						.setReason("未满10万交易的创客，点申请注销同步").insert();

				HandleRescissionApplyFormBean handleRescissionApplyFormBean = new HandleRescissionApplyFormBean();
				handleRescissionApplyFormBean.setId(apply.getId())
						.setRemark("未满10万交易的创客，点申请注销同步")
						.setState(2);
				return makerService.logOutOfSync(handleRescissionApplyFormBean, baseSimpleFormBean.getUserid());
			}
		}
		//选择线下付款方式-则同步到收费记录表，收费类型是“普票托管费”
		if (1 == formBean.getHandleType()) {
			RechargeRecord rechargeRecord = new RechargeRecord();
			//获取创客姓名
			MakerAccount account = new MakerAccount().selectOne(Condition.create().eq("userid", formBean.getUserid()));
			//新增收费记录
			rechargeRecord.setRechargeTypeId(Constants.RECHARGE_GENERAL_SERVICE_FEE)
					.setRechargeAmount(formBean.getHandleAmount())
					.setCustomerType(1)
					.setCustomerId(formBean.getUserid())
					.setCustomerName(account == null ? null : account.getRealname())
					.setRechargeRemark(formBean.getRemark())
					.setRechargeVoucher(formBean.getFilepath())
					.setCreatedBy(baseSimpleFormBean.getUserid())
					.setRechargeTime(new Date());
			rechargeRecord.insert();
		}

		return smartResult();
	}

	/**
	 * 导出 创客未满10万的 列表
	 *
	 * @param baseSimpleFormBean
	 * @param response
	 */
	public void exportNotUpStandardMakerList(BaseSimpleFormBean<NotUpStandardMakerFormBean> baseSimpleFormBean,
	                                         HttpServletResponse response) {

		NotUpStandardMakerFormBean reqdata = baseSimpleFormBean.getReqdata();
		// 增加 待处理 已处理 状态筛选
		int state = 0;
		if (reqdata.getType() == 1) {
			state = reqdata.getType();
		}
		Integer special = reqdata.getSpecial();
		if (special == null) {
			special = 0;
		}
		List<NotUpStandardMakerDto> list = makerMapper.notUpStandardMakerList(reqdata.getName(), state, special);
		String file = RandomUtil.createRandomNo("创客交易未满10万", "");
		try {
			EasyExcel.write(getExcelOutPutStream(response, file), NotUpStandardMakerDto.class).sheet("创客详情").doWrite(list);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 对创客 进行周期内 统计交易 金额
	 */
	public void statisticsMakerAccountTotalTransaction() {
		//查询所有满足条件的创客工作室和企业下的所有创客工作室
		List<MakerStudioPromiseDto> studioConfList = makerStudioMapper.getMaker();
		//承诺创客未满10万不收费
		Map<Integer,PlatformMemorandum> companyMap = new HashMap<>();
		Map<Integer,PlatformMemorandum> userStudioMap = new HashMap<>();
		List<PlatformMemorandum> companyStudioList = makerStudioMapper.queryStudioByCompany();
		List<PlatformMemorandum> userStudioList = makerStudioMapper.queryStudioByUserIds();
		if (CollectionUtils.isNotEmpty(companyStudioList)) {
			for (PlatformMemorandum dto:companyStudioList){
				companyMap.put(dto.getCustomerId(),dto);
			}
		}
		if (CollectionUtils.isNotEmpty(userStudioList)) {
			for (PlatformMemorandum dto:userStudioList){
				userStudioMap.put(dto.getCustomerId(),dto);
			}
		}
		if (CollectionUtils.isEmpty(studioConfList)) {
			return;
		}
		//获取当前日期
		Date today = DateUtil.getEndOfDay(new Date());
		//遍历所有创客，根据创客的免费周期新增数据/或修改金额
		for (MakerStudioPromiseDto studioConf : studioConfList) {
			int userId = studioConf.getUserid();
			//创客配置的免费年限 如果创客有特殊需求的话走创客的 如果没有走企业的
			int freeYears = 0;
			int freeType = 0;
			if (userStudioMap.containsKey(studioConf.getUserid())){
				freeType = userStudioMap.get(studioConf.getUserid()).getFreeType();
				if (freeType == 2){
					freeYears = platformMemorandumMapper.getFreeYears(studioConf.getUserid(),1);
				}
			}else {
				if (companyMap.containsKey(studioConf.getCompid())){
					freeType = companyMap.get(studioConf.getCompid()).getFreeType();
					if (freeType == 2){
						freeYears = platformMemorandumMapper.getFreeYears(studioConf.getCompid(),2);
					}
				}
			}
			//创客开户信息及创客承诺配置信息
			Date openFinishTime = studioConf.getOpenFinishtime();
			//计算开户日期和当前日期相差周期数
			int diff = DateUtil.yearDiffPeriod(openFinishTime, today);
			//遍历已经过去的周期，判断新增
			for (int i = 0; i < diff; i++) {
				Date from = DateUtil.getYearCycleStartDate(openFinishTime, i);
				Date to = DateUtil.getYearCycleEndDate(openFinishTime, i);
				String yearCycleStr = DateUtil.getYearCycleStr(from, to);
				int yearMark = DateUtil.getMonthFromDate(from, 1);

				// 先查询 当前是否 已添加记录
				MakerCycleRecord cycleRecord = new MakerCycleRecord().selectOne(
						Condition.create().eq("userid", userId).eq("year_mark", yearMark));
				boolean isInsert = cycleRecord != null ? true : false;
				//如果是永久免费 不做处理 存在的数据列表进行物理删除处理 是否特殊处理
				if (freeType == 1){
					if (isInsert){
						makerCyCleRecordMapper.deleteById(cycleRecord.getId());
					}
					continue;
				}
				//如果是自定义的话 年份设置几年处理几条
				if (freeType == 2){
					//统计限免次数
					int count = makerCyCleRecordMapper.specialHandlingCount(cycleRecord.getUserid());
					int state = 1;
					if (count >= freeYears){
						state = 0;
					}
					if (isInsert) {
						update(from, to, state, cycleRecord,freeType);
					} else {
						insert(from, to, state, userId, yearMark, yearCycleStr,freeType);
					}
				}
				//如果不存在特殊需求 默认走正常的
				if(freeType == 0) {
					if (isInsert) {
						update(from, to, 0, cycleRecord,freeType);
					} else {
						insert(from, to, 0, userId, yearMark, yearCycleStr,freeType);
					}
				}
			}
		}
	}

	public void insert(Date from, Date to, int state, int userId, int yearMark, String yearCycleStr,int freeType) {
		BigDecimal totalAmount = coreProjectService.getTotalAmountByUserId(userId, from, to);
		//获取金额
		MakerCycleRecord record = new MakerCycleRecord();
		record.setState(state);
		record.setTotalAmount(totalAmount);
		record.setUserid(userId);
		record.setYearMark(yearMark);
		record.setYearCycle(yearCycleStr);
		//记录特殊需求处理
		if (freeType == 2 && record.getState() > 0){
			record.setSpecialHandling(1);
			//已处理的数据增加处理记录
			MakerHandle makerHandle = new MakerHandle();
			makerHandle.setUserid(userId);
			makerHandle.setHandleYear(yearMark);
			makerHandle.setHandleType(5);
			makerHandle.setCreatetime(new Date());
			makerHandle.setRemark("承诺不收费：年限:" + yearMark);
			makerHandle.insert();
		}
		record.insert();

		log.info("新增承诺数据：userid:{},getYearMark:{},getYearCycle:{},金额：{},是否解决：{}", record.getUserid(), record.getYearMark(),
				record.getYearCycle(), record.getTotalAmount(), (state == 1 ? "是" : "否"));

	}

	public void update(Date from, Date to, int state, MakerCycleRecord record,int freeType) {
		//如果之前是已处理的状态，不更新状态
		if (record.getState() <= 0) {
			record.setState(state);
		}
		//记录特殊需求处理
		if (freeType == 2 && state > 0){
			record.setSpecialHandling(1);
			//从待处理变更已处理的数据增加处理记录
			MakerHandle makerHandle = new MakerHandle();
			makerHandle.setUserid(record.getUserid());
			makerHandle.setHandleYear(record.getYearMark());
			makerHandle.setHandleType(5);
			makerHandle.setCreatetime(new Date());
			makerHandle.setRemark("承诺不收费：年限:" + record.getYearMark());
			makerHandle.insert();
		}
		BigDecimal totalAmount = coreProjectService.getTotalAmountByUserId(record.getUserid(), from, to);
		record.setTotalAmount(totalAmount);
		record.updateById();
		log.info("修改承诺数据：userid:{},getYearMark:{},getYearCycle:{},金额：{},是否解决：{}", record.getUserid(), record.getYearMark(),
				record.getYearCycle(), record.getTotalAmount(), (state == 1 ? "是" : "否"));
	}

	/**
	 * 计算处理状态
	 *
	 * @param freeType    配置的免费年限类型
	 * @param freeYears   配置的免费年限
	 * @param endNowYears 截止到现在共几个免费年限
	 * @param currYear    当前在第几个年限,从0开始，第一个年限=0
	 * @return
	 */
	public int getState(int freeType, int freeYears, int endNowYears, int currYear) {
		int state = 1;
		if (freeType == 2) {
			//如果配置的免费年限 小于 到现在到免费年限，根据第几个年限判断收费
			if (freeYears < endNowYears) {
				int d = endNowYears - (endNowYears - freeYears);
				if (d < (currYear + 1)) {
					state = 0;
				}
			}
		}
		return state;
	}

	/**
	 * 按月统计每个商务名下企业交易金额
	 *
	 * @param baseSimpleFormBean
	 * @return
	 */
	public SmartResult statisticCorporateAmount(BaseSimpleFormBean<QueryCompanyAmountFromBean> baseSimpleFormBean) {
		QueryCompanyAmountFromBean fromBean = baseSimpleFormBean.getReqdata();
		int year = fromBean.getYear();
		int month = fromBean.getMonth();
		String name = fromBean.getName();
		Page<CorporateAmountDto> page = PageHelper.startPage(baseSimpleFormBean.getPage(), baseSimpleFormBean.getRows());
		List<CorporateAmountDto> amountDtoList = companyAccountMapper.statisticCorporateAmount(year, month, name);
		return smartResult(amountDtoList, page.getTotal(), page.getPages(), page.getPageNum());
	}

	/**
	 * 按月统计每个商务名下企业交易金额明细
	 *
	 * @param baseSimpleFormBean
	 * @return
	 */
	public SmartResult statisticCorporateAmountInfo(BaseSimpleFormBean<QueryCompanyAmountFromBean> baseSimpleFormBean) {
		QueryCompanyAmountFromBean fromBean = baseSimpleFormBean.getReqdata();
		int year = fromBean.getYear();
		int month = fromBean.getMonth();
		String name = fromBean.getName();
		Page<CorporateAmountDtoInfo> page = PageHelper.startPage(baseSimpleFormBean.getPage(), baseSimpleFormBean.getRows());
		List<CorporateAmountDtoInfo> amountDtoList = companyAccountMapper.statisticCorporateAmountInfo(year, month, name);
		return smartResult(amountDtoList, page.getTotal(), page.getPages(), page.getPageNum());
	}

	/**
	 * 导出商务企业下的交易金额
	 *
	 * @param fromBean
	 */
	public void exportBusinessCorporateAmount(QueryCompanyAmountFromBean fromBean, HttpServletResponse response) {
		int year = fromBean.getYear();
		int month = fromBean.getMonth();
		String name = fromBean.getName();
		List<CorporateAmountDto> amountDtoList = companyAccountMapper.statisticCorporateAmount(year, month, name);

		String file = RandomUtil.createRandomNo("商务企业下的交易金额", "");
		try {
			EasyExcel.write(getExcelOutPutStream(response, file), CorporateAmountDto.class).sheet("商务详情").doWrite(amountDtoList);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 按月统计跟单员的企业交易额
	 *
	 * @param baseSimpleFormBean
	 * @return
	 */
	public SmartResult statisticMerchandiser(BaseSimpleFormBean<QueryCompanyAmountFromBean> baseSimpleFormBean) {
		QueryCompanyAmountFromBean fromBean = baseSimpleFormBean.getReqdata();
		int year = fromBean.getYear();
		int month = fromBean.getMonth();
		Page<CompanyMerchandiserDto> page = PageHelper.startPage(baseSimpleFormBean.getPage(), baseSimpleFormBean.getRows());
		List<CompanyMerchandiserDto> amountDtoList = companyAccountMapper.statisticMerchandiser(year, month);
		return smartResult(amountDtoList, page.getTotal(), page.getPages(), page.getPageNum());
	}

	/**
	 * 按企业主体统计企业总余额
	 *
	 * @param baseSimpleFormBean
	 * @return
	 */
	public SmartResult<PartyAmountDto> queryCompanyAmountByParty(BaseSimpleFormBean baseSimpleFormBean) {
		Page<CompanyMerchandiserDto> page = PageHelper.startPage(baseSimpleFormBean.getPage(), baseSimpleFormBean.getRows());
		List<PartyAmountDto> amountDtoList = companyAccountMapper.queryCompanyAmountByParty();
		List<MakerAlipayPrincipalDto> list = makerAlipayPrincipalMapper.listValid();
		Map<String, MakerAlipayPrincipalDto> aliPayMap = list.stream().collect(Collectors.toMap(MakerAlipayPrincipalDto::getName, Function.identity(), (key1, key2) -> key2));
		for (PartyAmountDto dto : amountDtoList){
			if(aliPayMap.get(dto.getPartyName()) != null){
				dto.setAlipayBalance(aliPayMap.get(dto.getPartyName()).getAvailableAmount());
				dto.setAlipayAccountBalance(balanceService.queryAlipayAccountQuery(aliPayMap.get(dto.getPartyName()).getId()));
			}
			PaymentMerchant merchant = new PaymentMerchant().selectOne(Condition.create()
																				.eq("name", dto.getPartyName())
																				.last("limit 1"));

			if (merchant != null) {
				dto.setZhaoShangBankBalance(balanceService.queryZhaoShangBalance(merchant.getId()));
			}
			PaymentMerchant merchantPingan = new PaymentMerchant().selectOne(Condition.create()
					.eq("name", dto.getPartyName())
					.eq("payment_comp", 4)
					.last("limit 1"));
			if (merchantPingan != null) {
				dto.setPinganAccountBalance(balanceService.queryPinganAccountQuery(merchantPingan.getId()));
			}
		}
		return smartResult(amountDtoList, page.getTotal(), page.getPages(), page.getPageNum());
	}

	public SmartResult queryCompanyAmountByPartyList(BaseSimpleFormBean<CompanyAccountBalanceFormBean> formBean){
		CompanyAccountBalanceFormBean reqdata = formBean.getReqdata();
		Page<CompanyMerchandiserDto> page = PageHelper.startPage(formBean.getPage(), formBean.getRows());
		List<CompanyBalanceBriefDto> list = companyAccountMapper.queryCompanyAmountByPartyList(reqdata.getName(),reqdata.getPartyId(),reqdata.getWhetherSubject());
		return smartResultPage(page);
	}

	/**
	 * 导出企业余额
	 *
	 * @return
	 */
	public void exportCompanyAmount(HttpServletResponse response,CompanyAccountBalanceFormBean formBean) {
		List<CompanyBalanceBriefDto> briefList = companyAccountMapper.exportAccountBalanceList(formBean.getName());
		String file = RandomUtil.createRandomNo("企业余额", "");
		try {
			EasyExcel.write(getExcelOutPutStream(response, file), CompanyBalanceBriefDto.class).sheet("企业余额").doWrite(briefList);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public SmartResult<NonTradingMakerDto> getNonTradingMaker(BaseSimpleFormBean baseSimpleFormBean) {
		Page<NonTradingMakerDto> page = PageHelper.startPage(baseSimpleFormBean.getPage(), baseSimpleFormBean.getRows());
		List<NonTradingMakerDto> list = companyAccountMapper.getNonTradingMaker();
		return smartResult(list, page.getTotal(), page.getPages(), page.getPageNum());
	}

	public SmartResult getTaxerAmount(BaseSimpleFormBean<GetAmountFromBean> formBean) {
		GetAmountFromBean fromBean = formBean.getReqdata();
		int year = fromBean.getYear();
		int month = fromBean.getMonth();
		int merchandiserId = fromBean.getMerchandiserId();
		List<GetAmountDto> amountDtoList = companyAccountMapper.getTaxerAmount(year, month, merchandiserId);
		return smartResult(amountDtoList);
	}

	public SmartResult getAmount(BaseSimpleFormBean<GetAmountFromBean> formBean) {
		GetAmountFromBean fromBeans = formBean.getReqdata();
		int year = fromBeans.getYear();
		int month = fromBeans.getMonth();
		int merchandiserId = fromBeans.getMerchandiserId();
		int projectType = fromBeans.getProjectType();
		List<GetAmountDto> amountDtoList = companyAccountMapper.getAmount(year, month, merchandiserId, projectType);
		return smartResult(amountDtoList);
	}

	public void exportAmount(HttpServletResponse response, GetAmountFromBean formBean) {
		int year = formBean.getYear();
		int month = formBean.getMonth();
		int merchandiserId = formBean.getMerchandiserId();
		LocalDate localDate = new LocalDate(year, month, 1);
		Date years = localDate.toDate();

		List<GetAmountDto> amountDtoList = companyAccountMapper.getAmount(year, month, merchandiserId, 0);
		Map<Integer, GetAmountDto> appleMaps = amountDtoList.stream()
				.collect(Collectors.toMap(GetAmountDto::getCompanyid, a -> a, (k1, k2) -> k1));

		//获取纯代理交易金额
		List<GetAmountDto> amount = companyAccountMapper.getTaxerAmount(year, month, merchandiserId);
		for (GetAmountDto lists : amount) {
			if (appleMaps.containsKey(lists.getCompanyid())) {
				for (GetAmountDto list : amountDtoList) {
					if (lists.getCompanyid() == list.getCompanyid()) {
						list.setTaxerAmount(lists.getTaxerAmount());
					}
				}
			} else {
				amountDtoList.add(lists);
			}
		}

		Map<Integer, GetAmountDto> appleMap = amountDtoList.stream()
				.collect(Collectors.toMap(GetAmountDto::getCompanyid, a -> a, (k1, k2) -> k1));
		List<GetAmountDto> getEnterprise = companyAccountMapper.getEnterprise(years, merchandiserId);
		for (GetAmountDto dto : getEnterprise) {
			if (appleMap.containsKey(dto.getCompanyid()) == false) {
				amountDtoList.add(dto);
			}
		}
		String file = RandomUtil.createRandomNo("跟单员导出月度交易额", "");
		try {
			EasyExcel.write(getExcelOutPutStream(response, file), GetAmountDto.class).sheet("跟单员导出月度交易额").doWrite(amountDtoList);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public SmartResult<CompanyZhaoshangSubLedgerIncomingRecordDto> listZhaoshangIncomingRecords(
			BaseSimpleFormBean<ZhaoshangSubLedgerIncomingRecordListFormBean> formBean) {
		ZhaoshangSubLedgerIncomingRecordListFormBean reqdata = formBean.getReqdata();
		int merchantId = reqdata.getMerchantId();
		int operationType = reqdata.getOperationType();
		String name = reqdata.getName();
		int state = reqdata.getState();
		Date from = DateUtil.defaultInitial(reqdata.getFrom());
		Date to = DateUtil.defaultNow(reqdata.getTo());
		String orderNo = reqdata.getOrderNo();

		Page<CompanyZhaoshangSubLedgerIncomingRecordDto> page = PageHelper.startPage(formBean.getPage(), formBean.getRows());
		companyZhaoshangSubLedgerIncomingRecordMapper.list(0, name, merchantId, orderNo, state, operationType, from, to);
		return SmartResult.ofPage(page);
	}

	public SmartResult<PaymentMerchantDto> listZhaoshangMerchant() {
		return SmartResult.success(paymentMerchantMapper.listZhaoshangMerchant());
	}

	public SmartResult verifyZhaoshangIncomingRecordOperation(BaseSimpleFormBean<VerifyIncomingRecordOperationFormBean> formBean) {
		VerifyIncomingRecordOperationFormBean reqdata = formBean.getReqdata();
		int userid = formBean.getUserid();
		int verify = reqdata.getVerify();
		String note = reqdata.getNote();
		int id = reqdata.getId();

		CompanyZhaoshangSubLedgerIncomingRecord record = new CompanyZhaoshangSubLedgerIncomingRecord().selectById(id);
		Asserts.notNull(record, StatusMsg.StatusMsg_478);
		// Check this record need to mannually operate.
		Asserts.notEquals(record.getState(), CompanyZhaoshangSubLedgerIncomingRecordState.PENDING, StatusMsg.StatusMsg_483);
		// 满足2个状态可以转账：正常的手动审核充值，以及延迟处理的手动处理
		Asserts.isTrue(NumberUtil.intIn(record.getState(), CompanyZhaoshangSubLedgerIncomingRecordState.VERIFYING,
				CompanyZhaoshangSubLedgerIncomingRecordState.DELAYED), StatusMsg.StatusMsg_482);
		if (verify == 1) {
			// Auto-recharge
			record.setOperationType(CompanyZhaoshangSubLedgerIncomingRecordOperationType.MANUAL_RECHARGE)
					.setState(CompanyZhaoshangSubLedgerIncomingRecordState.PROCESSING);
			zhaoShangTradeBulterService.transferLedgerIncoming2Principal(record);
		} else {
			// refund
			record.setOperationType(CompanyZhaoshangSubLedgerIncomingRecordOperationType.REFUND)
					.setState(CompanyZhaoshangSubLedgerIncomingRecordState.PROCESSING);
		}
		record.setAdminid(userid).setNote(note).updateById();
		return SmartResult.success();
	}

	public SmartResult saveZhaoshangIncomingRefundReceipt(BaseSimpleFormBean<ZhaoshangIncomingRefundReceiptFormBean> formBean) {
		ZhaoshangIncomingRefundReceiptFormBean reqdata = formBean.getReqdata();
		String receipt = reqdata.getReceipt();
		int id = reqdata.getId();
		CompanyZhaoshangSubLedgerIncomingRecord record = new CompanyZhaoshangSubLedgerIncomingRecord().selectById(id);
		Asserts.notNull(record, StatusMsg.StatusMsg_478);

		record.setReceipt(receipt).setState(CompanyZhaoshangSubLedgerIncomingRecordState.HANDLED).updateById();

		return SmartResult.success();
	}

	public void exportStatisticCorporateAmount(HttpServletResponse response, ExportStatisticCorporateAmountFromBean formBean) {
		int year = formBean.getYear();
		int month = formBean.getMonth();
		int merchandiserId = formBean.getBusinessManagerId();

		List<ExportStatisticCorporateAmountDto> amountDtoList = companyAccountMapper.exportStatisticCorporateAmountDetail(year, month, merchandiserId);

		String file = RandomUtil.createRandomNo("商务导出月度交易额", "");
		try {
			EasyExcel.write(getExcelOutPutStream(response, file), ExportStatisticCorporateAmountDto.class).sheet("商务导出月度交易额").doWrite(amountDtoList);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 申请退款列表
	 */
	public SmartResult<RequestRefundListDto> requestRefundList(BaseSimpleFormBean<RequestRefundListFromBean> formBean) {
		RequestRefundListFromBean reqdata = formBean.getReqdata();
		Page<RequestRefundListDto> page = PageHelper.startPage(formBean.getPage(), formBean.getRows());
		enterpriseRefundMapper.requestRefundList(reqdata.getCompanyName(),reqdata.getState());
		return SmartResult.ofPage(page);
	}

	/**
	 * 取消申请退款
	 */
	public SmartResult cancellationForARefund(BaseSimpleFormBean<ConfirmRequestForRefundFromBean> formBean) {
		ConfirmRequestForRefundFromBean reqdata = formBean.getReqdata();
		EnterpriseRefund enterpriseRefund = enterpriseRefundMapper.selectById(reqdata.getId());
		if (enterpriseRefund == null) return emptyDataSmartResult();
		CompanyAccount companyAccount = companyAccountMapper.getByCompid(enterpriseRefund.getCompId());

		//判断退款状态
		if (enterpriseRefund.getState() != 1) return smartResult(StatusMsg.StatusMsg_374);
		// 查询企业支付方式余额
		CompanyPayment companyPayment = companyPaymentMapper.getCompanyPayment(enterpriseRefund.getCompId(),enterpriseRefund.getPayId());
		if (companyPayment == null) return smartResult(StatusMsg.StatusMsg_330);

		BigDecimal beforeBalance = companyPayment.getBalance();
		BigDecimal currBalance = companyPayment.getBalance().add(enterpriseRefund.getAmountOfMoney());

		//确认完成,生成企业流水
		CompanyAccountflow companyAccountflow = new CompanyAccountflow();
		companyAccountflow.setCompid(enterpriseRefund.getCompId())
				.setFlowAmount(enterpriseRefund.getAmountOfMoney())
				.setPayId(enterpriseRefund.getPayId())
				.setBeforeBalance(beforeBalance)
				.setCurrBalance(currBalance)
				.setBizid(enterpriseRefund.getId())
				.setBizType(CompanyAccountFlowBizType.BUSINESSES_APPLY_FOR_A_REFUND_CANCEL)
				.setFlowtype(1)
				.setFlowname("取消企业申请退款")
				.setPayId(companyPayment.getPayId());

		if (!companyAccountflow.insert()){
			return smartResult(StatusMsg.StatusMsg_375);
		}
		//修改撤销状态
		enterpriseRefund.setState(2)
				.setReasonForCancellation(reqdata.getReasonForCancellation())
				.updateById();
		//扣除的金额恢复
		companyPayment.setBalance(currBalance).updateById();
		Company company = new Company().selectById(enterpriseRefund.getCompId());
		wxMessageService.enterpriseApplicationDorRefund(company.getOpenid(),1,reqdata.getReasonForCancellation(),enterpriseRefund.getAmountOfMoney(),companyAccount.getBusinessManagerId());
		return smartResult();
	}

	/**
	 * 确认申请退款
	 */
	public SmartResult confirmRequestForRefund(BaseSimpleFormBean<ConfirmRequestForRefundFromBean> formBean) {
		ConfirmRequestForRefundFromBean reqdata = formBean.getReqdata();
		EnterpriseRefund enterpriseRefund = enterpriseRefundMapper.selectById(reqdata.getId());
		if (enterpriseRefund == null) return emptyDataSmartResult();
		//同意退款
		enterpriseRefund.setState(3)
				.setUploadReceipt(reqdata.getUploadReceipt())
				.setOperatorsId(formBean.getUserid())
				.setConfirmRefundTime(new Date());
		if (!enterpriseRefund.updateById()){
			return smartResult(StatusMsg.StatusMsg_199);
		}
		//发送消息
		Company company = new Company().selectById(enterpriseRefund.getCompId());
		wxMessageService.enterpriseApplicationDorRefund(company.getOpenid(),2,null,enterpriseRefund.getAmountOfMoney(),0);
		return smartResult();
	}
	/**
	 * 创建企业充值
	 */
	public SmartResult<AmountTopUpDto> amountTopUp(BaseSimpleFormBean<AmountTopUpFormBean> formBean) {
		AmountTopUpFormBean reqdata = formBean.getReqdata();
		if (reqdata.getCompId() == null || StringUtils.isEmpty(reqdata.getAmount())) return errorParamSmartResult();

		//检查企业是否存在
		int count = new Company().selectCount(Condition.create().eq("compid", reqdata.getCompId()));
		if (count == 0) return smartResult(StatusMsg.StatusMsg_302);
		AmountTopUpDto amountTopUpDto = new AmountTopUpDto();

		CompanyRecharge recharge = companyRechargeMapper.equalAmount(reqdata.getCompId(),DateUtil.getCurrentTime(15),reqdata.getAmount());
		boolean equalAmount = recharge != null;
		CompanyZhaoshangSubLedgerRecharge ledgerRecharge = ledgerRechargeMapper.ledgerRecharge(reqdata.getCompId());
		boolean usedSmartRecharge = ledgerRecharge != null;
		amountTopUpDto.setEqualAmount(equalAmount);
		amountTopUpDto.setUsedSmartRecharge(usedSmartRecharge);
		return smartResult(amountTopUpDto);
	}
}
